首页 > 解决方案 > java中的逻辑与错误。无法进行二进制 AND

问题描述

我是java新手,我正在学习按位运算符。当我运行以下代码时,它会引发错误。我不知道是什么错误。我替换它仍然&&给出&错误。

class Main{
    
    public static void main(String []args){

      int n=5, k=3;
        if (n && (1<<(k-1)!=0))  //THIS LINE GIVING ERROR
            System.out.println("Mahima! bit is set");
        else
            System.out.println("Mahima!  bit is not set");
        
    
    }
}

下面是错误。

  Line 6: error: bad operand types for binary operator '&&' [in Main.java]
            if (n && (1<<(k-1)!=0))
                  ^
      first type:  int
      second type: boolean

当我使用一个 & 我得到以下错误

Line 6: error: bad operand types for binary operator '&' [in Main.java]
        if (n & (1<<(k-1)!=0))  //THIS LINE GIVING ERROR
              ^
  first type:  int
  second type: boolean

标签: javadata-structurescompiler-errorsbit-manipulationbitwise-operators

解决方案


首先,您将&&运算符更改为&.
&&逻辑与运算符。它需要两个booleans 并返回一个boolean
&按位和运算符。它需要两个ints 并返回一个int

更改&&为后&,您必须添加一些括号,因为!=它的优先级高于&

if ((n & (1<<(k-1))) !=0)
    System.out.println("Mahima! bit is set");
else
    System.out.println("Mahima!  bit is not set");

推荐阅读