在 Java 中,if 条件必须是一个布尔表达式(结果为 true 或 false),不能像某些语言那样写 if(a)(a 为非布尔类型)。下面从基本写法 → 常见错误 → 正确示例给你说明。
if (条件) {
// 条件为 true 时执行
}
示例:
int age = 18;
if (age >= 18) {
System.out.println("成年人");
}
if (条件) {
// true
} else {
// false
}
if (条件1) {
} else if (条件2) {
} else {
}
==,不是 =// 错误
if (a = 5) { } // 编译错误(除非 a 是 boolean)
// 正确
if (a == 5) { }
boolean flag = true;
if (flag) { } // 正确
if (flag == true) { } // 也可以,但没必要
equalsString s = "hello";
if (s.equals("hello")) { } // 正确
if (s == "hello") { } // 可能错误
if (a > 0 && a < 10) { }
if (x == 1 || x == 2) { }
if (obj != null) { }
❌ 非布尔类型当条件
int a = 5;
if (a) { } // 编译错误
❌ 赋值当比较
if (x = 10) { } // 错误
❌ 少括号(虽然有时能编,但不推荐)
if (a == 1)
System.out.println("a");
System.out.println("b"); // 不属于 if
✅ 推荐始终加 {}
int score = 85;
if (score >= 90) {
System.out.println("优秀");
} else if (score >= 60) {
System.out.println("及格");
} else {
System.out.println("不及格");
}
如果你有具体代码报错 / 不知道条件怎么写,直接把代码贴出来,我可以帮你改 ✅
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。