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");
}
}
}我得到了错误,我无法理解为什么,因为我是新的Java和编程。
二进制运算符
<=的坏操作数类型
if (51 <= x <= 9) {
first type: boolean
second type: int
1 error发布于 2016-03-09 19:49:04
Java的工作方式:首先计算51 <= x <= 9 51 <= x,这会导致代码中出现false (布尔值)。然后在<= 9中尝试这一结果。因此,错误"<=对布尔值和int无效“。
正如在其他答案中所建议的那样,您必须使用&& (和)运算符。例如:
if (x <= 51 && x >= 9) {
//do something
}正如您在我的答案中所看到的,我使用了“小于”和“大于”,这有助于阅读代码。读起来就好像x小于51,x大于9一样。
希望这有助于解释。
发布于 2016-03-09 19:00:31
使用此代码而不是您的代码修复问题。
51 <= x && x <= 9您的问题是,第一次比较返回布尔值,然后将其与int值进行比较。这是错误的。
比较是一种二进制操作,从左到右依次处理。
发布于 2016-03-09 19:12:26
在Java中使用来自另一种语言的语法(可能是Python),您需要这样做:
if (51 <= x && x <= 9)示例
int x = 60;
if (51 <= x && x <= 9) {
System.out.println("Let's do something using Java technology.");
} else {
System.out.println("Let's");
}https://stackoverflow.com/questions/35900277
复制相似问题