「if」文
CoddyのDartジャーニー「基礎」セクションの一部 — レッスン 31/94。
Dart の if文 は、ブール条件を評価し、その条件が true の場合にのみコードを実行します。
if (condition) {
// 条件が true の場合に実行するコード
}数値が正の数であるかをチェックする例:
void main() {
int number = 10;
if (number > 0) {
print('The number is positive');
}
}任意のブール式を条件として使用できます:
void main() {
int age = 20;
bool hasLicense = true;
if (age >= 18 && hasLicense) {
print('You can drive');
}
}チャレンジ
簡単生徒の点数に基づいて、試験に合格したか不合格かを判定するプログラムを作成してください:
- 名前が
examScoreの整数変数を宣言し、値を 68 に設定してください - 名前が
passingGradeの定数整数を宣言し、値を 70 に設定してください if文を使用して、生徒の点数が合格点未満かをチェックしてください- 点数が合格点未満の場合、
Exam status: Failed. You need to improve by X points.を出力してください(X は合格点に達するために必要な点数です) - 点数が合格点以上(等しいを含む)の場合、
Exam status: Passed. Good job!を出力してください
出力は期待される形式と完全に一致する必要があります。
チートシート
Dart の if 文 は、ブール条件を評価し、その条件が true の場合にのみコードを実行します:
if (condition) {
// 条件が true の場合に実行するコード
}簡単な条件を使った例:
int number = 10;
if (number > 0) {
print('The number is positive');
}論理演算子を使った複雑なブール式を使用できます:
int age = 20;
bool hasLicense = true;
if (age >= 18 && hasLicense) {
print('You can drive');
}自分で試してみよう
void main() {
// ここで変数を宣言してください
int examScore = _;
const int passingGrade = _;
// ここに if 文を書いてください
if (_) {
int pointsNeeded = _;
print("Exam status: Failed. You need to improve by $pointsNeeded points.");
} else {
print("Exam status: Passed. Good job!");
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。