java - 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
解决方案
首先,您将&&
运算符更改为&
.
&&
是逻辑与运算符。它需要两个boolean
s 并返回一个boolean
。
&
是按位和运算符。它需要两个int
s 并返回一个int
。
更改&&
为后&
,您必须添加一些括号,因为!=
它的优先级高于&
:
if ((n & (1<<(k-1))) !=0)
System.out.println("Mahima! bit is set");
else
System.out.println("Mahima! bit is not set");
推荐阅读
- python - 为什么我无法进入数据库?jacky@本地主机密码:NO
- google-apps-script - 需要帮助在谷歌表格中创建一个简单的宏来从数据创建多个图表
- javascript - 使用 express 和 node.js 在 ejs 模板中插入用户名
- java - 需要知道以下给定格式的数字格式
- c++ - 为什么我们可以这样做: Base *base = new Derived; 而我们不能做 Derived *derived = new Base?
- php - DomDocument 在样式元素中从文件中插入 CSS
- flutter - 在颤动中从 listView 导航页面
- excel - 将 vba 查找和替换限制为活动工作表
- php - CakePHP 4 自定义插件找不到类
- styles - Material-UI 主题:如何管理 .MuiXXX 类的应用顺序或优先级?