第6天:理解 Java 的 if、else if 和 else 语句
发布: (2025年12月25日 GMT+8 01:43)
2 分钟阅读
原文: Dev.to
Source: Dev.to
什么是条件语句?
Java 中的条件语句用于在条件为真时控制程序的执行流程。当程序需要针对不同的输入表现出不同的行为时,这非常有用。
if 语句
if 语句在括号内检查一个条件。
- 如果条件为真,代码块内部的代码将会执行。
- 如果条件为假,代码块将被跳过。
示例
int score = 60;
if (score >= 50) {
System.out.println("You passed the exam!");
}
else if 语句
当第一个 if 条件为假时,else if 语句用于检查另一个条件。
示例
int score = 75;
if (score >= 90) {
System.out.println("Excellent!");
} else if (score >= 50) {
System.out.println("You passed.");
}
else 语句
当上述所有条件都不满足时,else 语句会执行。
示例
int score = 40;
if (score >= 90) {
System.out.println("Excellent!");
} else if (score >= 50) {
System.out.println("You passed.");
} else {
System.out.println("You failed.");
}
记忆简易规则
if→ 检查第一个条件else if→ 检查其他条件else→ 当所有条件都为假时执行
在 if–else if–else 结构中只能执行一个代码块。
当日任务
将账户余额设为 5000。
- 如果余额低于 5000,显示:
"Withdrawal successfully" - 如果余额高于 5000,显示:
"Withdrawal Failed"
示例代码
package demo;
public class Sample {
public static void main(String[] args) {
int balance = 4500;
if (balance > 5000) {
System.out.println("Withdrawal Failed!");
} else {
System.out.println("Withdrawal successfull");
}
}
}
说明
balance当前被设为4500。- 由于余额小于
5000,程序会打印 “Withdrawal successfull”。 - 如果余额大于
5000,则会打印 “Withdrawal Failed!”。