분기와 표현식
Coddy의 C# 개발자를 위한 Dart 코스 레슨. 48개 중 8번째.
C#과 Dart의 조건 연산자는 두 결과 분기 중 하나를 선택합니다. Dart의 if는 문이며, 결과가 없는 것이 허용되는지는 null 허용 여부에 따라 결정됩니다.
if 문이나 조건식에는 Boolean 조건을 사용하세요. 조건식은 선택된 결과만 평가합니다. 함수가 null을 허용하지 않는 타입을 반환한다고 약속하는 경우, 모든 일반적인 경로에 호환되는 결과를 지정하세요.
완전한 C# 프로그램:
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main(){int width=8,height=8;Console.WriteLine(width==height?"square":"rectangle");}
}
완전한 Dart 프로그램:
void main(){final width=8,height=8;final shape=width==height?'square':'rectangle';print(shape);}챌린지
쉬움fare(int stops)를 구현하세요. 정류장이 0개부터 2개까지이면 2를, 3개부터 5개까지이면 5를, 그보다 많으면 9를 반환하세요. 입력은 0부터 100까지의 정수 하나입니다.
편집 가능한 파일에서 출력하지 마세요. 제공된 exercise.dart는 입력을 파싱하고 출력을 반환합니다. 잠긴 드라이버는 공개 API를 별도로 테스트하고 결과를 줄바꿈 문자 하나와 함께 출력합니다.
코드는 functions.dart, exercise.dart에 작성하세요. main.dart에는 제공된 입력/출력 코드가 있으며 편집할 수 없습니다.
직접 해보기
import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'functions.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
check(fare(4)==5 && fare(20)==9);
stdout.writeln(solve(input));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C# 개발자를 위한 Dart의 모든 레슨
직접 연습해 보세요: 온라인 Dart 컴파일러