[英]I am getting a error of type mismatch from int to boolean
The code is to check whether a number is even or odd using the last bit is 1 or 0. if last bit is 1 it will go in if and print odd 代码是检查一个数字是偶数还是奇数,最后一位是1还是0.如果最后一位为1,它将进入if和print odd
import java.util.Scanner;
public class Even_or_odd {
public void Check_even_or_odd(int a) {
if(a&1)//error:Type mismatch: cannot convert from int to boolean
System.out.println("odd");
else
System.out.println("even");
}
public static void main(String[] args) {
System.out.println("enter a number to check even or odd");
Scanner scan=new Scanner(System.in);
int a=scan.nextInt();
scan.close();
Even_or_odd e=new Even_or_odd();
e.Check_even_or_odd(a);
}
}
Your code tests a
for being odd/even by masking its binary representation with 1
, which has all bits set to zero except least significant one, which is set to 1
. 您的代码通过使用
1
屏蔽其二进制表示来测试a
奇数/偶数,其中所有位都设置为零,除了最低有效值(设置为1
。
Odd numbers will produce 1
when masked with 1
; 奇数将产生
1
时屏蔽1
; even numbers will produce zero. 偶数将产生零。 However, you cannot write
if (1)
or if (0)
, because there is no implicit conversion from int
to boolean
in Java. 但是,你不能写
if (1)
或if (0)
,因为在Java中没有从int
到boolean
隐式转换。 You need to write 你需要写
if ((a&1) != 0)
to fix this problem. 解决这个问题。
Instead of binary operations, which is what I guess you are trying to do, check the input value using modulo: 而不是二进制操作,这是我想你要做的,使用模数检查输入值:
if (a % 2 == 0) {
System.out.println("even");
} else {
System.out.println("odd");
}
In the condition block of the if statement you have to have a boolean value or an expression that evaluates to a boolean. 在if语句的条件块中,您必须具有布尔值或计算结果为布尔值的表达式。
a&1
evaluates to an integer. a&1
计算为整数。
Also see Check whether number is even or odd 另请参阅检查数字是偶数还是奇数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.