I am trying to see if the multidimensional array is rectangular or not. I am new to programming and can't exactly figure out why the "break;" will not kick me out of the loop and it continues to run. Even with the array not being rectangular, I still get back true.
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;
}
}
}
}
In order to avoid labels, put your code into a method that returns a boolean:
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 can be improved to support arguments checks and whatnot, but the point is you return from the method as soon as you determine your answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With