[英]Java - error: incompatible types: int cannot be converted to boolean
考虑操作:(7>>1)&1
当我们输入 print 语句时,它起作用了: System.out.println((7>>1)&1); // 有效
但是如果我们输入 if 条件就会出错:
if((7>>1)&1) System.out.println('这里'); # 显示错误
错误:不兼容的类型:int 无法转换为 boolean if((7>>1)&1) System.out.println(123);
我无法理解可能是什么问题? 由于相同的作品在 C++..
我尝试分配给变量 int a=(7>>1)&1
if(a==1) System.out.println('works'); // 它在这里有效,但在直接传递时无效
正如 SmallPepperZ 所述,在 java 中, if
语句不接受除boolean
原始类型之外的任何参数,或者可以评估为boolean
原始类型的语句。
为了扩展 SmallPepperZ 的答案,你的第二个问题的原因,要求使用变量a
,是因为表达式是通过以下方式计算的:
if( (7>>1)&1 == 1 )
if( 3 & 1 == 1 )
if( 3 & true )
您会看到的错误应该是以下内容:
The operator & is undefined for the argument type(s) int, boolean
要解决此问题,请在左侧的表达式周围添加一组括号
if( ((7>>1)&1) == 1 ) System.out.println("Here");
通过以下方式进行评估:
if( ((7>>1)&1) == 1 )
if( ((3)&1) == 1 )
if( (3&1) == 1 )
if( 1 == 1 )
if( true )
与 C++ 不同,Java 不会将整数1
和0
解释为等同于布尔值true
和false
请参阅为什么Java中的boolean只取true或false? 为什么不是 1 或 0 呢? 想要查询更多的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.