This question already has answers here:
bad operand types for binary operator “&” java
(3个答案)
5个月前关闭。
我正在尝试使用按位&运算符打印偶数和奇数,但不解释为什么它不与三元运算符一起工作。
(3个答案)
5个月前关闭。
我正在尝试使用按位&运算符打印偶数和奇数,但不解释为什么它不与三元运算符一起工作。
class Geeks {
static void evenOdd (int a,int b)
{
int e = (a&1==0)?a:b;// error: bad operand types for binary operator '&'
System.out.println(e);
int o = (a&1==1)?a:b;// error: bad operand types for binary operator '&'
System.out.print(o);
}
}
最佳答案
这是由于使用了运算符的优先级。
由于==的优先级高于&,因此对1 == 0进行求值。它评估为布尔结果。由于&获得2个操作数-一个布尔值和一个整数。由于&可以在相同类型上执行,因此会导致编译错误。
与加法之前执行乘法的原因相同(称为BODMAS)
在这种情况下,必须使用括号:
System.out.println(e);
int o = ((a&1)==1)?a:b;
System.out.print(o);
关于java - 二进制运算符的错误操作数类型&,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58499112/