uma*_*lah 0 java if-statement boolean logical-operators
class First {
public static void main(String[] arguments) {
int x =60;
if (51 <= x <= 9) {
System.out.println("Let's do something using Java technology.");
} else {
System.out.println("Let's");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我收到错误,但我不明白为什么,因为我是 Java 和编程新手。
二元运算符的错误操作数类型
<=
if (51 <= x <= 9) {
first type: boolean
second type: int
1 error
Run Code Online (Sandbox Code Playgroud)
小智 5
Java 的工作原理:51 <= x <= 9
51 <= x首先计算,这会导致代码中出现 false(布尔值)。然后用 尝试其结果<= 9。因此会出现错误“<= 对于布尔值和 int 无效”。
正如其他答案中所建议的,您将必须使用&&(和)运算符。例如:
if (x <= 51 && x >= 9) {
//do something
}
Run Code Online (Sandbox Code Playgroud)
正如您在我的回答中看到的,我使用了小于和大于,这有助于阅读代码。读起来就好像x小于等于 51 并且x大于等于 9。
希望这有助于解释。