如何在主方法中访问布尔数组的辅助方法?

huangapple go评论151阅读模式
英文:

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;

<kbd>Ideone演示</kbd>

这种行为称为自动装箱和拆箱。然而,尽管数组在协变性方面是协变的,但它们只在对象层次结构内是协变的,而不适用于包装类型。这就是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.

<kbd>Ideone demo</kbd>


Explanation:

Boolean is the wrapper-class for the primitive boolean. Thus, one can write

boolean b1 = true;
Boolean booleanObject = b;
boolean b2 = booleanObject;

<kbd>Ideone demo</kbd>

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()==truegetVegetarian.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 :-)

huangapple
  • 本文由 发表于 2020年8月24日 06:30:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63552649.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定