Java 如何检查布尔数组的所有元素都为真

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18631837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:41:38  来源:igfitidea点击:

How to check ALL elements of a boolean array are true

javaarraysboolean

提问by Daybreak

I have a boolean array whose size depends on the size of a randomly selected string.

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

So I have something like this:

所以我有这样的事情:

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

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?

这给了我一个越界异常错误。我也尝试过contains()方法,但即使数组中的 1 个元素为真,也会结束循环。我是否需要一个遍历数组所有元素的 for 循环?如何在其中设置测试条件?

采纳答案by Peter Walser

Using the enhanced for loop, you can easily iterate over an array, no need for indexes and size calculations:

使用增强的 for 循环,您可以轻松迭代数组,无需索引和大小计算:

private static boolean allTrue (boolean[] values) {
    for (boolean value : values) {
        if (!value)
            return false;
    }
    return true;
}

回答by Prabhakaran Ramaswamy

boolean[] foundLetterArray = new boolean[5]; The memory allocation for the abow array is like

boolean[] foundLetterArray = new boolean[5]; abow 数组的内存分配就像

      foundLetterArray[0],foundLetterArray[1],foundLetterArray[2],foundLetterArray[3],foundLetterArray[4] 

Array index starts with 0 and the total memory count is 5 and the last array index is 4.

数组索引从 0 开始,总内存数为 5,最后一个数组索引为 4。

You are trying to get index 5 that is foundLetterArray[5] which does not exist. That's why you are getting the ArrayIndexOutofBoundsException

您正在尝试获取不存在的 foundLetterArray[5] 索引 5。这就是为什么你得到ArrayIndexOutofBoundsException

   if(foundLetterArray[selectedWord.length()-1]==true){
      System.out.println("You have reached the end");
   }

回答by Nargis

Arrays in Java starts from index 0and last index is always [array.length()-1]

Java 中的数组index 0始终从最后一个索引开始[array.length()-1]

As you are checking for foundLetterArray[selectedWord.length()],its giving you a array out of Bound Exception try foundLetterArray[selectedWord.length()-1]

当您正在检查时foundLetterArray[selectedWord.length()],它会为您提供一个超出 Bound Exception 的数组尝试foundLetterArray[selectedWord.length()-1]

Like:

喜欢:

if(foundLetterArray[selectedWord.length()-1]){
System.out.println("You have reached the end");
}

回答by Nargis

Indices in java, as well as most programming languages, are 0-based, meaning that individual elements in an array with n elements have indices 0, 1, 2, ..., n-1. The last element in an array is always at index array.length - 1.

Java 以及大多数编程语言中的索引都是从 0 开始的,这意味着具有 n 个元素的数组中的各个元素具有索引 0、1、2、...、n-1。数组中的最后一个元素始终位于索引 array.length - 1 处。

回答by Satyam Koyani

Array index start from 0 so last index is always 1 less then array length so here you are trying to access last index + 1 by doing foundLetterArray[selectedWord.length()] this so it is throuing ArrayIndexBoundEception use array.lastIndex() method or subtract 1 form length.

数组索引从 0 开始,所以最后一个索引总是比数组长度小 1,所以在这里你试图通过执行 foundLetterArray[selectedWord.length()] 来访问最后一个索引 + 1,所以它通过 ArrayIndexBoundEception 使用 array.lastIndex() 方法或减去 1 个表格长度。

Implementing this foundLetterArray[selectedWord.length()-1]You must take care about one thing if your array does not contains any elements then selectedWord.length() return 0 and again you will get same exception so Its good to check lengh before doing this foundLetterArray[selectedWord.length()-1].

实现这foundLetterArray[selectedWord.length()-1]一点如果您的数组不包含任何元素,则您必须注意一件事,然后 selectedWord.length() 返回 0 并且您将再次获得相同的异常,因此在执行此操作之前检查 lengh 是件好事foundLetterArray[selectedWord.length()-1]

回答by Tom McIntyre

do this

做这个

public boolean allTrue(boolean[] array) {
    for (boolean b : array) {
        if (!b) {
           return false;
        }
    }
    return true;
}

There is no 'one line' way of knowing whether all of the elements of an array meet a certain condition (there are libraries that take care of the looping for you, but you still need to write the condition). Querying array[x] will only tell you about the xth item in that array, so for your question you need to check every item.

没有“一行”的方法可以知道数组的所有元素是否满足特定条件(有些库会为您处理循环,但您仍然需要编写条件)。查询 array[x] 只会告诉您该数组中的第 x 个项目,因此对于您的问题,您需要检查每个项目。

Also, as other people have pointed out, array indices are 0-based, so the first element is at array[0] and the last at array[array.length() - 1].

此外,正如其他人所指出的,数组索引是从 0 开始的,因此第一个元素在 array[0] 处,最后一个元素在 array[array.length() - 1] 处。

My example uses an alternate looping construct known as for-each. This is appropriate when you don't need to modify the array contents, you only need to read from them. It avoids any messing around with indices.

我的示例使用称为 for-each 的备用循环结构。当您不需要修改数组内容时,这很合适,您只需要从中读取。它避免了对索引的任何混淆。

回答by Tom McIntyre

You do the check only for last element in the array ( and do it wrong, above is described why ).

您只检查数组中的最后一个元素(并且做错了,上面描述了原因)。

In order to get if arrays contains only true values you should check all of them.

为了确定数组是否仅包含真值,您应该检查所有这些值。

boolean allAreTrue = true;
for (boolean val : foundLetterArray) {
  allAreTrue = allAreTrue && val;
}

// at this line allAreTrue will contain true if all values are true and false if you have at least one "false"

// 在这一行,如果所有值都为真,则 allAreTrue 将包含真,如果您至少有一个“假”,则为假

回答by Paul Boddington

There is a Java 8 one-liner for this:

有一个 Java 8 one-liner:

boolean allTrue(boolean[] arr) {
    return IntStream.range(0, arr.length).allMatch(i -> arr[i]);
}