0

I'm working on a project but I feel stumped on this particular section. I need to create a method that returns a boolean value true if all entries in a 2d array are false, and returns false when as little as 1 of those values is true. currently, my code inside the method resembles this:

int counter = 0;
  for (int i = 0; i < lightArray.length; i++){
     for(int j = 0; j <lightArray[0].length; i++) {
        if (lightArray[i][j] == false) {
           counter++;
           if (counter == lightArray.length * lightArray[0].length) {
              return true;
           }
        }
        else {
           return false;
        }
     }
  }

My initital thought was that i would use a 'counter' variable so that the if statement would only return true if there was a 'counter' for every value in lightArray. After testing, it doesn't seem to register when all values are set to false.

I also tried a version of the code where this section

if (lightArray[i][j] == false) {
           counter++;
           if (counter == lightArray.length * lightArray[0].length) {
              return true;

}

just read as this:

if (lightArray[i][j] == false) {
              return true;

with no 'counter' variable involved at all, but when that code is in place, the method returns true as soon as it hits a single false value.

Is there another way that I am just not thinking of that I can check every value in the 2D array before returning a boolean?

2
  • "the method returns true as soon as it hits a single false value." Have it do the opposite: return false as soon as it hits a single true value. If you go through the entire array without that happening, then you know that it contains only false values. Commented Dec 6, 2017 at 22:35
  • wow yeah thanks I should have seen that, and I appreciate the advice Commented Dec 6, 2017 at 23:07

1 Answer 1

1

Usually the logic like you have should be in this form:

loop{
    if (negative_condition) return false;            
}
return true;

Notice that return true is outside of the loop.

In your case you have nested loop which should looks like this:

loop{
    loop{
        if (negative_condition) return false;  
    }          
}
return true;

Looking at the above pseudo code, your Java code should look like this:

for (int i = 0; i < lightArray.length; i++){
    for(int j = 0; j <lightArray[0].length; j++) {
       if (lightArray[i][j] == true) return false;
    }
 }

 return true;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.