How to check ALL elements of a boolean array are true(如何检查布尔数组的所有元素是否为真)
问题描述
我有一个布尔数组,其大小取决于随机选择的字符串的大小.
I have a boolean array whose size depends on the size of a randomly selected string.
所以我有这样的事情:
boolean[] foundLetterArray = new boolean[selectedWord.length()];
随着程序的进行,这个特殊的布尔数组会被数组中每个元素的真实值填充.我只想在数组的所有元素都为真后立即打印一条语句.所以我试过了:
As the program progresses, this particular boolean array gets filled with true values for each element in the array. I just want to print a statement as soon as all the elements of the array are true. So I have tried:
if(foundLetterArray[selectedWord.length()]==true){
System.out.println("You have reached the end");
}
这给了我一个越界异常错误.我也尝试过 contains()
方法,但即使数组中的 1 个元素为真,它也会结束循环.我是否需要一个遍历数组所有元素的 for 循环?我该如何设置测试条件?
This gives me an out of bounds exception error. I have also tried contains()
method but that ends the loop even if 1 element in the array is true. Do I need a for loop that iterates through all the elements of the array? How can I set a test condition in that?
推荐答案
使用增强的for循环,可以轻松遍历数组,无需索引和大小计算:
Using the enhanced for loop, you can easily iterate over an array, no need for indexes and size calculations:
private static boolean allTrue (boolean[] values) {
for (boolean value : values) {
if (!value)
return false;
}
return true;
}
这篇关于如何检查布尔数组的所有元素是否为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检查布尔数组的所有元素是否为真


- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01