Cannot convert from int to boolean?

笑着哭i 提交于 2021-02-05 10:47:05

问题


public static void main(String[] args) {
    int [] newArray= new int [4];
    int [] array = {4,5,6,7};
    oddEven(array);

    newArray[0] = array[0]+array[1]+array[2]+array[3];
    newArray[1] = array[0]*array[1]*array[2]*array[3];
}

public static void oddEven(int [] oddEven) {

    for (int i=0; i<oddEven.length; i++) {
        //  Cannot convert from int to boolean
        if (oddEven[i] % 2)

    }
}

Ignore what I'm trying to manage here. I'm only curious why it doesn't accept "if" statement in this for loop. As I stated it says "cannot convert from int to boolean". Why do you think it says so?


回答1:


That expression in side the if should be realizes to boolean value, otherwise compilation error in java.

Try

       if (oddEven[i] % 2 ==0)  {
       }

or even (based on requirment)

       if (oddEven[i] % 2 !=0)  {
       }

See the Language Specification# chapter 14

The Expression must have type boolean or Boolean, or a compile-time error occurs.



来源:https://stackoverflow.com/questions/19357071/cannot-convert-from-int-to-boolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!