[英]bad operand types for binary operator '<='
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");
}
}
}
I am getting the error and I cant understand why as I am new to Java and programming. 我收到错误,我不明白为什么我不熟悉Java和编程。
bad operand types for binary operator
<=
二元运算符的坏操作数类型
<=
if (51 <= x <= 9) {
first type: boolean
second type: int
1 error
Use this code instead of yours to fix problem 使用此代码而不是您的代码来解决问题
51 <= x && x <= 9
Your trouble is because first comparison returns boolean value and after you compare it with int value. 您的麻烦是因为第一次比较返回布尔值并将其与int值进行比较。 It's wrong.
这是不对的。
Comparison is a binary operation, that processed from left to right one by one. 比较是二进制操作,从左到右逐个处理。
How Java works for: 51 <= x <= 9
51 <= x
is calculated first which results to a false (boolean) in your code. Java的工作原理:
51 <= x <= 9
51 <= x
首先计算得到代码中的false(布尔值)。 Then the result of that is tried with <= 9
. 然后用
<= 9
尝试结果。 And therefore the error, "<= not valid for boolean and int". 因此错误,“<=对布尔和int无效”。
As suggested in other answers you will have to use &&
(and) operator. 如其他答案所示,您将不得不使用
&&
(和)运算符。 For Example: 例如:
if (x <= 51 && x >= 9) {
//do something
}
As you can see in my answer I have used both less than and greater than, which helps in reading code. 正如你在我的回答中所看到的,我使用了小于和大于,这有助于阅读代码。 Read as if
x
is less than equal to 51 and x
is greater than equal to 9 then. 读取好像
x
小于等于51且x
大于等于9。
Hope this helps in explanation. 希望这有助于解释。
You should use logical operator &&
meaning and . 你应该使用逻辑运算符
&&
含义和 。 Others are ||
其他人是
||
meaning or and negation !
意义或 否定
!
. 。 You can make various combinations using these operators and brackets
()
. 您可以使用这些运算符和括号
()
进行各种组合。
Your condition should be like this one: 你的情况应该是这样的:
if (51 <= x && x <= 9) {
You are using syntax from another language (Python maybe) in Java you need to do: 您正在使用Java中的另一种语言(可能是Python)的语法:
if (51 <= x && x <= 9)
example 例
int x = 60;
if (51 <= x && x <= 9) {
System.out.println("Let's do something using Java technology.");
} else {
System.out.println("Let's");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.