如何检查布尔数组中的所有元素都为真 [英] How to check ALL elements of a boolean array are true

查看:136
本文介绍了如何检查布尔数组中的所有元素都为真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个布尔数组的大小取决于在随机选择的字符串的大小。

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");
}

这给了我一个出界异常错误的。我也曾尝试包含()方式,但最终即使数组中的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;
}

这篇关于如何检查布尔数组中的所有元素都为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆