提问人:potapov.alexey 提问时间:5/31/2023 更新时间:5/31/2023 访问量:21
在 Java 中检查 KeyBox 对象的布尔数组中的值
Checking values in a boolean array of a KeyBox object in Java
问:
我用 和 对象创建了一个类。
如何检查 box 对象的值是否为 。KeyBox
boolean[] cells
KeyBox
box = new KeyBox(new boolean[3])
cell
false
我的代码是:
public class KeyBox {
static int numberCells = 3;
boolean[] cells;
public KeyBox(boolean[] cells) {
this.cells = cells;
}
public static void main(String[] args) {
KeyBox box = new KeyBox(new boolean[numberCells]);
PutKey.put(box);
}
}
public class PutKey {
public static void put(KeyBox box) {
boolean isTrue = Arrays.asList(box.cells).stream().findAny().equals("false");
System.out.println(isTrue);
}
}
默认情况下获取值,我希望会得到.boolean
false
sout isTrue
true
答:
0赞
Reilas
5/31/2023
#1
有几种不同的方法可以检查布尔数组是否包含特定值。
第一种是简单地遍历数组,当遇到 false 值时将 isTrue 设置为 true。
boolean isTrue = false;
for (boolean value : box.cells) {
if (!value) {
isTrue = true;
break;
}
}
System.out.println(isTrue);
如果要使用流(最初在代码中使用流),可以使用以下命令。
您必须首先将布尔数组转换为布尔列表。
List<Boolean> cells = new ArrayList<>();
for (boolean value : box.cells) cells.add(value);
boolean isTrue = cells.stream().anyMatch(b -> !b);
System.out.println(isTrue);
评论