1. 概述
在本篇文章中,我们将深入学习 Java 中 if-else
语句的使用方式。
作为所有控制结构中最基础的一种,if-else
也是编程中最常见的条件判断语句。它允许我们仅在满足特定条件时执行某段代码。
2. if-else
语法
if
语句必须使用一个布尔表达式作为其判断条件。
if (condition) {
// 条件为 true 时执行
} else {
// 条件为 false 时执行
}
其中,else
是可选的。如果布尔表达式为 false
,则会执行 else
块中的内容。
3. if
语句示例
我们从一个最简单的例子开始。
假设我们只想在变量 count
大于 1 时执行某段逻辑:
if (count > 1) {
System.out.println("Count is higher than 1");
}
只有当 count > 1
成立时,才会打印 "Count is higher than 1"
。
⚠️ 注意:虽然在只有一行代码的情况下可以省略大括号,但强烈建议始终加上大括号,以提升代码可读性。
当然,你也可以在代码块中添加更多语句:
if (count > 1) {
System.out.println("Count is higher than 1");
System.out.println("Count is equal to: " + count);
}
4. if-else
语句示例
通过组合使用 if
和 else
,我们可以在两个分支中选择一个执行:
if (count > 2) {
System.out.println("Count is higher than 2");
} else {
System.out.println("Count is lower or equal than 2");
}
❌ 注意:else
不能单独使用,必须与 if
配对。
5. if-else if-else
结构示例
最后我们来看一个完整的 if-else if-else
结构,用于在多个条件中进行选择:
if (count > 2) {
System.out.println("Count is higher than 2");
} else if (count <= 0) {
System.out.println("Count is less or equal than zero");
} else {
System.out.println("Count is either equal to one, or two");
}
✅ 这种结构非常适合处理多个互斥条件。
6. 总结
本文简要介绍了 Java 中 if-else
语句的基本语法和常见用法,它是控制程序流程的基础工具之一。
所有示例代码都可以在 GitHub 仓库 中找到。