Conditional violation for loops in Java
I am trying to see if a multidimensional array is rectangular or not. I'm new to programming and can't figure out exactly why "break;" will not kick me out of the loop and it keeps working. Even if the array is not rectangular, I will still return.
public static void main(String[] args) {
int a2d[][] = {{1, 2, 3, 4, 5}, {2, 3, 4}, {1, 2, 3, 4, 5}};
int test = a2d[0].length;
for (int i = 0; i < a2d.length; i++) {
for (int j = 0; j < a2d[i].length; j++) {
if (a2d[i].length == test) {
System.out.println("True");
} else {
System.out.println("False");
break;
}
}
}
}
source to share
To avoid shortcuts, put code into a method that returns a boolean value:
boolean isRectangular(int[][] a2d) {
int test = a2d[0].length;
for (int i=0; i<a2d.length; i++){
for (int j=0; j<a2d[i].length; j++){
if (a2d[i].length != test) {
return false;
}
}
}
return true;
}
The code could be improved to support argument checks and whatnot, but the bottom line is that you return from the method as soon as you define your answer.
source to share
Java 8's approach to the problem would look like this:
int a2d[][] = {{1, 2, 3, 4, 5}, {2, 3, 4}, {1, 2, 3, 4, 5}};
boolean isRectangular =
Arrays.stream(a2d) // First, create a stream
.map(row -> row.length) // Map the length of each row to process further
.allMatch(len -> len == a2d[0].length); // Verify the length of all rows
If used, no outer loop is required, which means no break. Also, the loop can be parallelized if needed (possibly speed up the work).
source to share
public static void main(String[] args) {
int a2d[][] = {{1,2,3,4,5},
{2,3,4},
{1,2,3,4,5}};
int test = a2d[0].length;
outer:
for (int i=0; i<a2d.length; i++){
for (int j=0; j<a2d[i].length; j++){
if (a2d[i].length == test) {
System.out.println("True");
} else {
System.out.println("False");
break outer;
}
}
}
}
This must be done. Google on labeled for loops
. This should help you.
source to share