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?
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.