ネストされた if - else
CoddyのC#ジャーニー「基礎」セクションの一部。レッスン 30/69。
if-else文を互いに入れ子にできます。これにより、階層的な意思決定構造を作成できます。
例:
if (age > 18) {
if (hasLicense) {
Console.WriteLine("You can drive");
} else {
Console.WriteLine("Get a license first");
}
} else {
Console.WriteLine("Too young to drive");
}
無限にネストすることができます:
if (condition1) {
if (condition2) {
if (condition3) {
// condition1、condition2、condition3がすべてtrueの場合
...
}
}
}波かっこがない場合、elseは、それより前にあるelseを持たない最も近いifと対応します。
if (age > 18)
if (hasLicense)
Console.WriteLine("You can drive");
else
Console.WriteLine("Get a license first");この場合、インデントにかかわらず、elseはif (hasLicense)に対応します。対応関係を明確にするには、波かっこを使いましょう。
チャレンジ
初心者ジェットコースターに乗れるかどうかを判定するプログラムを作成してください。条件は次のとおりです。
- 12歳以上であること
- 身長が150cmを超えていること
- 両方の条件を満たしていても、15歳未満の場合は大人の付き添いが必要です
各ケースで、status変数に次の文字列をそのまま設定してください。
- 年齢が低すぎる場合:
Sorry, you're too young - 身長が足りない場合:
Sorry, you're not tall enough - 15歳未満で大人がいない場合:
Sorry, you need an adult with you - 15歳未満で大人がいる場合:
You can ride with adult supervision! - 15歳以上で身長が十分な場合:
You can ride by yourself!
自分で試してみよう
using System;
class Program {
public static void Main(string[] args) {
int age = int.Parse(Console.ReadLine()); // この行を変更しないでください
int height = int.Parse(Console.ReadLine()); // この行を変更しないでください
bool hasAdult = bool.Parse(Console.ReadLine()); // この行を変更しないでください
string status = "";
// 以下にコードを書いてください
// この行より下を変更しないでください
Console.WriteLine(status);
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
基礎のすべてのレッスン
自分で練習してみよう: C#オンラインコンパイラ