if 关键字
概述
if
关键字用于条件判断,根据布尔表达式的结果决定是否执行代码块。它是程序控制流的基础语句。
语法格式
基本if语句
if (布尔表达式) {
// 当条件为true时执行的代码
}
if-else语句
if (布尔表达式) {
// 条件为true时执行
} else {
// 条件为false时执行
}
if-else if-else语句
if (布尔表达式1) {
// 条件1为true时执行
} else if (布尔表达式2) {
// 条件1为false,条件2为true时执行
} else if (布尔表达式3) {
// 前面条件都为false,条件3为true时执行
} else {
// 所有条件都为false时执行
}
基本用法
简单条件判断
public class IfExample {
public static void main(String[] args) {
int age = 18;
// 基本if语句
if (age >= 18) {
System.out.println("已成年,可以投票");
}
// if-else语句
if (age >= 18) {
System.out.println("成年人");
} else {
System.out.println("未成年人");
}
// 多条件判断
int score = 85;
if (score >= 90) {
System.out.println("优秀");
} else if (score >= 80) {
System.out.println("良好");
} else if (score >= 70) {
System.out.println("中等");
} else if (score >= 60) {
System.out.println("及格");
} else {
System.out.println("不及格");
}
}
}
复杂条件表达式
public class ComplexConditions {
public static void main(String[] args) {
int age = 25;
boolean hasLicense = true;
boolean hasInsurance = true;
double accountBalance = 10000.0;
// 逻辑AND操作
if (age >= 18 && hasLicense) {
System.out.println("可以开车");
}
// 逻辑OR操作
if (age < 18 || !hasLicense) {
System.out.println("不能开车");
} else {
System.out.println("可以开车");
}
// 复杂条件组合
if ((age >= 21 && hasLicense && hasInsurance) || accountBalance > 50000) {
System.out.println("可以租赁豪华车");
} else if (age >= 18 && hasLicense) {
System.out.println("可以租赁普通车");
} else {
System.out.println("不能租车");
}
// 字符串比较
String userRole = "admin";
if ("admin".equals(userRole)) {
System.out.println("管理员权限");
} else if ("user".equals(userRole)) {
System.out.println("普通用户权限");
} else {
System.out.println("游客权限");
}
// 空值检查
String name = "张三";
if (name != null && !name.isEmpty()) {
System.out.println("用户名:" + name);
} else {
System.out.println("用户名为空");
}
}
}
嵌套if语句
public class NestedIf {
public static void main(String[] args) {
int temperature = 25;
boolean isRaining = false;
boolean hasUmbrella = true;
if (temperature > 0) {
System.out.println("气温正常");
if (temperature > 30) {
System.out.println("天气炎热,建议穿短袖");
if (temperature > 35) {
System.out.println("高温预警,注意防暑");
}
} else if (temperature > 20) {
System.out.println("天气温暖,适合外出");
if (isRaining) {
if (hasUmbrella) {
System.out.println("带伞出门");
} else {
System.out.println("建议延迟外出或购买雨伞");
}
} else {
System.out.println("天气晴朗,适合户外活动");
}
} else {
System.out.println("天气较凉,建议穿外套");
}
} else {
System.out.println("气温过低,注意保暖");
}
}
}
实际应用示例
// 用户登录验证
public class LoginValidator {
public static boolean validateUser(String username, String password) {
// 输入验证
if (username == null || username.trim().isEmpty()) {
System.out.println("用户名不能为空");
return false;
}
if (password == null || password.length() < 6) {
System.out.println("密码长度至少6位");
return false;
}
// 格式验证
if (username.length() < 3) {
System.out.println("用户名长度至少3位");
return false;
}
if (!username.matches("[a-zA-Z0-9_]+")) {
System.out.println("用户名只能包含字母、数字和下划线");
return false;
}
// 模拟数据库验证
if ("admin".equals(username) && "admin123".equals(password)) {
System.out.println("管理员登录成功");
return true;
} else if ("user".equals(username) && "user123".equals(password)) {
System.out.println("用户登录成功");
return true;
} else {
System.out.println("用户名或密码错误");
return false;
}
}
public static void main(String[] args) {
validateUser("admin", "admin123");
validateUser("user", "123");
validateUser("", "password");
validateUser("guest", "guest123");
}
}
// 银行转账业务
public class BankTransfer {
public static void transfer(double fromBalance, double toBalance, double amount) {
System.out.println("转账前:发送方余额=" + fromBalance + ", 接收方余额=" + toBalance);
// 金额验证
if (amount <= 0) {
System.out.println("转账失败:转账金额必须大于0");
return;
}
if (amount > fromBalance) {
System.out.println("转账失败:余额不足");
return;
}
// 限额检查
if (amount > 50000) {
System.out.println("转账失败:单笔转账不能超过50000元");
return;
}
// 执行转账
fromBalance -= amount;
toBalance += amount;
System.out.println("转账成功:金额=" + amount);
System.out.println("转账后:发送方余额=" + fromBalance + ", 接收方余额=" + toBalance);
// 余额提醒
if (fromBalance < 1000) {
System.out.println("提醒:您的账户余额不足1000元");
}
}
public static void main(String[] args) {
transfer(5000, 2000, 1500); // 正常转账
transfer(1000, 2000, 2000); // 余额不足
transfer(10000, 2000, -500); // 金额无效
transfer(60000, 2000, 55000); // 超过限额
}
}
三元运算符替代简单if
public class TernaryOperator {
public static void main(String[] args) {
int a = 10, b = 20;
// 传统if-else
String result1;
if (a > b) {
result1 = "a较大";
} else {
result1 = "b较大或相等";
}
// 三元运算符(推荐用于简单条件)
String result2 = (a > b) ? "a较大" : "b较大或相等";
System.out.println("传统方式:" + result1);
System.out.println("三元运算符:" + result2);
// 嵌套三元运算符(不推荐,可读性差)
int score = 85;
String grade = (score >= 90) ? "A" :
(score >= 80) ? "B" :
(score >= 70) ? "C" :
(score >= 60) ? "D" : "F";
System.out.println("成绩等级:" + grade);
}
}
最佳实践
条件表达式要清晰:
// 好的做法 if (user != null && user.isActive() && user.hasPermission("READ")) { // 处理逻辑 } // 避免复杂难懂的条件 if (!(user == null || !user.isActive() || !user.hasPermission("READ"))) { // 处理逻辑 }
使用早期返回减少嵌套:
// 好的做法 public void processUser(User user) { if (user == null) { return; } if (!user.isValid()) { return; } // 主要逻辑 } // 避免深层嵌套 public void processUser(User user) { if (user != null) { if (user.isValid()) { // 主要逻辑 } } }
合理使用括号:
// 使用括号明确优先级 if ((age >= 18 && hasLicense) || isEmergency) { // 逻辑清晰 }
常见错误
赋值vs比较:
int x = 5; if (x = 10) { // 错误:应该用==比较 System.out.println("x等于10"); } if (x == 10) { // 正确 System.out.println("x等于10"); }
空指针问题:
String str = null; if (str.equals("hello")) { // 错误:可能空指针异常 System.out.println("匹配"); } if ("hello".equals(str)) { // 正确:避免空指针 System.out.println("匹配"); }
浮点数比较:
double a = 0.1 + 0.2; if (a == 0.3) { // 错误:浮点数精度问题 System.out.println("相等"); } if (Math.abs(a - 0.3) < 0.0001) { // 正确:使用精度范围 System.out.println("相等"); }
if语句是Java程序控制流的基础,掌握其正确使用方法对编写逻辑清晰的程序至关重要。