二元运算符“&”java的错误操作数类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23095004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bad operand types for binary operator "&" java
提问by user3364498
The error shows this line
错误显示这一行
if ((a[0] & 1 == 0) && (a[1] & 1== 0) && (a[2] & 1== 0)){
This is the whole code:
这是整个代码:
public class Ex4 {
public static void main(String[] args) {
int [] a = new int [3];
if(args.length == 3)
{
try{
for(int i = 0; i < args.length; i++)
{
a[i] = Integer.parseInt(args[i]);
}
}
catch(NumberFormatException e){
System.out.println("Wrong Argument");
}
if ((a[0] & 1 == 0) && (a[1] & 1== 0) && (a[2] & 1== 0)){
System.out.println("yes");
}
else {
System.out.println("no");
}
}
else{
System.out.println("Error");
}
}
}
I've fixed the code:
我已经修复了代码:
if ((a[0] & 1) == 0 && (a[1] & 1) == 0 && (a[2] & 1) == 0){
Was an issue with the brackets, updated for anyone in the future.
括号有问题,将来为任何人更新。
采纳答案by Sotirios Delimanolis
==
has higher precedence than &
. You might want to wrap your operations in ()
to specify how you want your operands to bind to the operators.
==
具有比 更高的优先级&
。您可能希望将您的操作包装起来,()
以指定您希望操作数如何绑定到操作符。
((a[0] & 1) == 0)
Similarly for all parts of the if
condition.
对于if
条件的所有部分也是如此。
回答by AntonH
You have to be more precise, using parentheses, otherwise Java will not use the order of operands that you want it to use.
您必须更精确,使用括号,否则 Java 将不会使用您希望它使用的操作数的顺序。
if ((a[0] & 1 == 0) && (a[1] & 1== 0) && (a[2] & 1== 0)){
Becomes
成为
if (((a[0] & 1) == 0) && ((a[1] & 1) == 0) && ((a[2] & 1) == 0)){
回答by fge
Because &
has a lesserpriority than ==
.
由于&
具有较小的比优先级==
。
Your code is equivalent to a[0] & (1 == 0)
, and unless a[0]
is a boolean this won't compile...
您的代码等效于a[0] & (1 == 0)
, 除非a[0]
是布尔值,否则将无法编译...
You need to:
你需要:
(a[0] & 1) == 0
etc etc.
等等等等
(yes, Java does hava a boolean &
operator -- a non shortcut logical and)
(是的,Java 确实有一个布尔&
运算符——一个非捷径逻辑和)