Java 无法从 int 转换为 boolean?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19357071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot convert from int to boolean?
提问by Nik
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?
忽略我在这里尝试管理的内容。我只是好奇为什么它不接受这个 for 循环中的“if”语句。正如我所说,它说“无法从 int 转换为 boolean”。你认为它为什么这么说?
采纳答案by Suresh Atta
That expression in side the if
should be realizes to boolean
value, otherwise compilation error in java.
里面的那个表达式if
应该被实现为boolean
值,否则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.
表达式必须具有 boolean 或 Boolean 类型,否则会发生编译时错误。