If–Else If Chains
メニューを表示するにはスワイプしてください
What Are If–Else If Chains?
An if–else if chain lets you check several conditions, one after another. You use this when you need your program to make decisions based on more than two possible situations. Kotlin checks each condition in order and runs the code for the first one that is true.
Basic Structure
Here is the general structure of an if–else if chain in Kotlin:
if (condition1) {
// Code runs if condition1 is true
} else if (condition2) {
// Code runs if condition2 is true
} else {
// Code runs if none of the above conditions are true
}
You can have as many else if branches as you need. The else branch is optional, but it is useful for handling all the remaining cases.
How It Works
- Kotlin checks the first condition;
- If it is false, Kotlin checks the next
else ifcondition; - This continues until a condition is true, then only that block runs;
- If none are true, the
elseblock runs (if it exists).
Example: Grading System
Suppose you want to assign a letter grade based on a student's score:
package com.example
fun main() {
val score = 76
if (score >= 90) {
println("Grade: A")
} else if (score >= 80) {
println("Grade: B")
} else if (score >= 70) {
println("Grade: C")
} else if (score >= 60) {
println("Grade: D")
} else {
println("Grade: F")
}
}
In this example:
- If the score is 90 or above, the program prints
Grade: A; - If the score is 80 or above (but less than 90), it prints
Grade: B; - If the score is 70 or above (but less than 80), it prints
Grade: C; - If the score is 60 or above (but less than 70), it prints
Grade: D; - If none of these are true, it prints
Grade: F.
When to Use If–Else If Chains
- When you need to check multiple, exclusive conditions;
- When each outcome should be handled differently;
- When the order of conditions matters for your logic.
If–else if chains are a clear and simple way to handle decision-making in your Kotlin programs.
すべて明確でしたか?
フィードバックありがとうございます!
セクション 2. 章 3
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 2. 章 3