英文:
How can I access a helper method for a boolean array in my main method?
问题
我正在写作
这是我目前的进展:
import java.util.Scanner;
新的 Boolean[count];
}
我在哪里?
英文:
I am writing
This is what I have so far:
import java.util.Scanner;
ew Boolean[count];
}
}
Where am I g
答案1
得分: 5
Boolean[]
和boolean[]
不同。将Boolean[] vegetarian = new Boolean[count];
改为boolean[] vegetarian = new boolean[count];
就可以工作了。
解释:
Boolean
是基本类型boolean
的包装类。因此,可以这样写:
boolean b1 = true;
Boolean booleanObject = b;
boolean b2 = booleanObject;
这种行为称为自动装箱和拆箱。然而,尽管数组在协变性方面是协变的,但它们只在对象层次结构内是协变的,而不适用于包装类型。这就是Boolean[]
不能赋值给boolean[]
,反之亦然的原因。
英文:
Boolean[]
and boolean[]
are not the same. Change Boolean[] vegetarian = new Boolean[count];
to boolean[] vegetarian = new boolean[count];
and it will work.
Explanation:
Boolean
is the wrapper-class for the primitive boolean
. Thus, one can write
boolean b1 = true;
Boolean booleanObject = b;
boolean b2 = booleanObject;
This behaviour is known as Autoboxing and -unboxing. However, even though arrays are covariant, they are only covariant within the object-hierachy, not to the wrapper types. This is the reason an Boolean[]
cannot be assigned to a boolean[]
and vice-versa.
答案2
得分: 1
你正在使用布尔值(Boolean),它是一个对象。你不能直接比较布尔对象和布尔基本类型。
尝试使用 getVegetarian.booleanValue()
,这会起作用!
if (list[i].booleanValue() == true) {
count++;
}
顺便说一下,你不必写成 getVegetarian.booleanValue()==true
,getVegetarian.booleanValue()
就足够了
英文:
you are using Boolean and that is an object. You cannot directly compare an Boolean object to a boolean primitive.
Try using getVegetarian.booleanValue(),
this will work!
if (list[i].booleanValue() == true) {
count++;
}
BTW you don't have to write getVegetarian.booleanValue()==true, getVegetarian.booleanValue() is enough :-)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论