我有一个 boolean 数组,其大小取决于随机选择的字符串的大小。
所以我有这样的东西:
boolean[] foundLetterArray = new boolean[selectedWord.length()];
随着程序的进行,这个特定的 boolean 数组会填充数组中每个元素的真值。我只想在数组的所有元素都为真时立即打印一条语句。所以我尝试过:
if(foundLetterArray[selectedWord.length()]==true){
System.out.println("You have reached the end");
}
这给了我一个越界异常错误。我也尝试过 contains()
方法,但即使数组中的 1 个元素为真,该方法也会结束循环。我是否需要一个遍历数组所有元素的 for 循环?如何在其中设置测试条件?
最佳答案
使用增强的for循环,您可以轻松地遍历数组,无需索引和大小计算:
private static boolean allTrue (boolean[] values) {
for (boolean value : values) {
if (!value)
return false;
}
return true;
}
关于java - 如何检查 boolean 数组的所有元素是否为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18631837/