Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
412 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...