在Java中进行位移时不兼容的类型错误

时间:2016-04-12 16:44:46

标签: java binary comparator bit-shift

我正在尝试对某些二进制对象执行按位AND比较:

private int selectedButtons = 0x00;

private static final int ABSENCE_BUTTON_SELECTED = 0x01;
private static final int SICKNESS_BUTTON_SELECTED = 0x02;
private static final int LATENESS_BUTTON_SELECTED = 0x04;

这是比较器:

    boolean absenceButtonEnabled = selectedButtons & ABSENCE_BUTTON_SELECTED;

但是我收到了这个错误:

Error:(167, 56) error: incompatible types
required: boolean
found:    int

有什么想法吗?

3 个答案:

答案 0 :(得分:4)

selectedButtons & ABSENCE_BUTTON_SELECTED是一个整数,因为&binary or运算符。

将其转换为布尔值:

boolean absenceButtonEnabled = (selectedButtons & ABSENCE_BUTTON_SELECTED) != 0;

答案 1 :(得分:2)

将其与零比较:

boolean absenceButtonEnabled = selectedButtons & ABSENCE_BUTTON_SELECTED != 0;

答案 2 :(得分:2)

两个int的返回类型为int。请尝试以下代码。

boolean absenceButtonEnabled = (selectedButtons & ABSENCE_BUTTON_SELECTED) == ABSENCE_BUTTON_SELECTED