Appearance
6.2 if 语句
if 语句的概念
if 语句是 Java 中最基本的选择结构,它根据条件的真假来决定是否执行一段代码。
if 语句的语法
java
if (条件表达式) {
// 条件为 true 时执行的代码
}- 条件表达式:一个返回布尔值的表达式
- 代码块:当条件表达式为 true 时执行的代码
if 语句的使用
基本用法
java
public class IfStatementExample {
public static void main(String[] args) {
int age = 18;
if (age >= 18) {
System.out.println("You are eligible to vote.");
}
}
}示例:检查数字的正负
java
public class CheckNumberExample {
public static void main(String[] args) {
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
}
if (number < 0) {
System.out.println("The number is negative.");
}
if (number == 0) {
System.out.println("The number is zero.");
}
}
}示例:检查字符串是否为空
java
public class CheckStringExample {
public static void main(String[] args) {
String name = "John";
if (name != null && !name.isEmpty()) {
System.out.println("Hello, " + name + "!");
}
}
}if 语句的嵌套
if 语句可以嵌套使用,即在一个 if 语句的代码块中包含另一个 if 语句。
java
public class NestedIfExample {
public static void main(String[] args) {
int age = 20;
boolean hasLicense = true;
if (age >= 18) {
System.out.println("You are an adult.");
if (hasLicense) {
System.out.println("You can drive.");
}
}
}
}if 语句与逻辑运算符的结合
java
public class IfWithLogicalOperatorsExample {
public static void main(String[] args) {
int score = 85;
if (score >= 60 && score <= 100) {
System.out.println("You passed the exam.");
}
String username = "admin";
String password = "123456";
if (username.equals("admin") && password.equals("123456")) {
System.out.println("Login successful.");
}
}
}if 语句的应用场景
1. 权限检查
java
if (user.isAdmin()) {
// 显示管理员功能
}2. 数据验证
java
if (email.contains("@")) {
// 邮箱格式有效
}3. 状态检查
java
if (order.isPaid()) {
// 处理已支付的订单
}示例:if 语句的使用
java
public class IfApplication {
public static void main(String[] args) {
// 检查年龄
int age = 25;
if (age < 13) {
System.out.println("You are a child.");
}
if (age >= 13 && age < 18) {
System.out.println("You are a teenager.");
}
if (age >= 18) {
System.out.println("You are an adult.");
}
// 检查成绩
int score = 95;
if (score >= 90) {
System.out.println("Excellent!");
}
// 检查温度
double temperature = 30.5;
if (temperature > 30) {
System.out.println("It's hot outside.");
}
// 检查是否为闰年
int year = 2024;
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
System.out.println(year + " is a leap year.");
}
}
}常见问题
1. 条件表达式错误
症状:条件表达式语法错误或逻辑错误
解决方案:确保条件表达式返回布尔值,检查逻辑是否正确
2. 代码块缺失
症状:if 语句后没有使用大括号,导致只有第一行代码被执行
解决方案:始终使用大括号包围 if 语句的代码块,即使只有一行代码
3. 嵌套过深
症状:if 语句嵌套层次过深,代码可读性差
解决方案:减少嵌套层次,使用逻辑运算符或提取方法
总结
if 语句是 Java 中最基本的选择结构,它根据条件的真假来决定是否执行一段代码。if 语句的语法简单明了,但功能强大,可以处理各种条件判断场景。
在使用 if 语句时,需要注意:
- 条件表达式必须返回布尔值
- 始终使用大括号包围代码块
- 避免嵌套过深,保持代码可读性
- 结合逻辑运算符处理复杂条件
通过合理使用 if 语句,可以使程序根据不同的条件执行不同的代码,实现复杂的业务逻辑。
