How to check ALL elements of a boolean array are true

27,316

Solution 1

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

Solution 2

There is a Java 8 one-liner for this:

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

Solution 3

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

      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.

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

   if(foundLetterArray[selectedWord.length()-1]==true){
      System.out.println("You have reached the end");
   }
Share:
27,316
Daybreak
Author by

Daybreak

Updated on March 06, 2020

Comments

  • Daybreak
    Daybreak about 4 years

    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?