Menu
Coddy logo textTech

ネストされた if-else

CoddyのRustジャーニー「Fundamentals」セクションの一部 — レッスン 28/75。

if-elif-else 文は、互いに入れ子(ネスト)にすることができます。これにより、階層的な意思決定構造を作成できます。

例えば:

if age > 18 {
    if hasLicense {
        println!("You can drive");
    } else {
        println!("Get a license first");
    }
} else {
    println!("Too young to drive");
}

無限にネストさせることができます:

if condition1 {
	if condition2 {
		if condition3 {
		    // condition1、condition2、およびcondition3が真の場合
		    ...
		}
	}
}
challenge icon

チャレンジ

初心者

ジェットコースターに乗れるかどうかを判定するプログラムを作成してください。要件は以下の通りです:

  • 12歳以上であること
  • 身長が150cmより高いこと
  • 両方の要件を満たしていても15歳未満の場合は、大人の同伴が必要

各ケースについて、以下のメッセージを正確に出力してください:

  • 年齢が足りない場合: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!

チートシート

if-elif-else文を互いに入れ子(ネスト)にして、階層的な意思決定構造を作成することができます:

if age > 18 {
    if hasLicense {
        println!("You can drive");
    } else {
        println!("Get a license first");
    }
} else {
    println!("Too young to drive");
}

ネストは無限に行うことができます:

if condition1 {
    if condition2 {
        if condition3 {
            // condition1、condition2、およびcondition3がすべて真(true)の場合
            ...
        }
    }
}

自分で試してみよう

use std::io;

fn main() {
    let mut age_input = String::new();
    let mut height_input = String::new();
    let mut adult_input = String::new();
    
    io::stdin().read_line(&mut age_input).unwrap();
    io::stdin().read_line(&mut height_input).unwrap();
    io::stdin().read_line(&mut adult_input).unwrap();
    
    let age: i32 = age_input.trim().parse().unwrap();
    let height: i32 = height_input.trim().parse().unwrap();
    let has_adult: bool = adult_input.trim().parse().unwrap();

    // 以下にコードを記述してください
    
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

Fundamentalsのすべてのレッスン