简体   繁体   English

我收到从int到boolean类型不匹配的错误

[英]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中没有从intboolean隐式转换。 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.

相关问题 为什么会出现类型不匹配错误? - Why am I getting Type mismatch error? 为什么我收到错误“类型不匹配”? - Why i am getting error “Type Mismatch”? 为什么我会收到此错误? “二元运算符“&&”的操作数类型错误 第一种类型:int 第二种类型:布尔值 - Why am I getting this error? "Bad operand type for binary operator "&&" first type: int second type: boolean" “类型不匹配:无法从 int 转换为布尔值”我不知道错误究竟是什么 - "Type mismatch: cannot convert from int to boolean" I don't know what the error actually is 类型不匹配:无法从 int 转换为 boolean - Type mismatch:could not convert from int to boolean 没有类型不匹配-从原始int到boolean的转换 - No type mismatch - conversion from primitive int to boolean 类型不匹配:无法从布尔值转换为整数 - Type mismatch: cannot convert from boolean to int 尽管未使用布尔值,但我收到“类型不匹配无法从int转换为布尔值” - I get “Type mismatch cannot convert from int to boolean” despite not using boolean 如何解决“类型不匹配:无法从 int 转换为 boolean”java 错误? - How to resolve “Type mismatch: cannot convert from int to boolean” java error? 类型不匹配:在while循环中无法从int转换为boolean - Type mismatch: cannot convert from int to boolean in while loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM