[英]Java - error: incompatible types: int cannot be converted to boolean
Considering operation: (7>>1)&1考虑操作:(7>>1)&1
When we put into print statement it works: System.out.println((7>>1)&1);当我们输入 print 语句时,它起作用了: System.out.println((7>>1)&1); // works
// 有效
But if we put in if condition there is error:但是如果我们输入 if 条件就会出错:
if((7>>1)&1) System.out.println('Here'); if((7>>1)&1) System.out.println('这里'); # shows error
# 显示错误
error: incompatible types: int cannot be converted to boolean if((7>>1)&1) System.out.println(123);
错误:不兼容的类型:int 无法转换为 boolean if((7>>1)&1) System.out.println(123);
I am unable to understand what could be the issue?我无法理解可能是什么问题? Since same works in C++..
由于相同的作品在 C++..
I tried assigning to a variable int a=(7>>1)&1我尝试分配给变量 int a=(7>>1)&1
if(a==1) System.out.println('works'); if(a==1) System.out.println('works'); // it works here but not when passed directly
// 它在这里有效,但在直接传递时无效
As SmallPepperZ stated, in java, if
statements do not accept any argument except the boolean
primitive type, or a statement that can be evaluated to the boolean
primitive type.正如 SmallPepperZ 所述,在 java 中,
if
语句不接受除boolean
原始类型之外的任何参数,或者可以评估为boolean
原始类型的语句。
To expand on SmallPepperZ answer, the reason for your second issue, requiring that the variable a
be used, is due to the fact that the expression gets evaluated in the following way:为了扩展 SmallPepperZ 的答案,你的第二个问题的原因,要求使用变量
a
,是因为表达式是通过以下方式计算的:
if( (7>>1)&1 == 1 )
if( 3 & 1 == 1 )
if( 3 & true )
The error you would have seen should have been the following:您会看到的错误应该是以下内容:
The operator & is undefined for the argument type(s) int, boolean
To fix this, add a set of parenthesis around the expression on the left要解决此问题,请在左侧的表达式周围添加一组括号
if( ((7>>1)&1) == 1 ) System.out.println("Here");
which gets evaluated in the following way:通过以下方式进行评估:
if( ((7>>1)&1) == 1 )
if( ((3)&1) == 1 )
if( (3&1) == 1 )
if( 1 == 1 )
if( true )
Java does not interpret the integers 1
and 0
as equivalent to the booleans true
and false
, unlike C++与 C++ 不同,Java 不会将整数
1
和0
解释为等同于布尔值true
和false
See Why boolean in Java takes only true or false?请参阅为什么Java中的boolean只取true或false? Why not 1 or 0 also?
为什么不是 1 或 0 呢? for more information.
想要查询更多的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.