Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally breaking for loops in Java [duplicate]

Tags:

java

loops

break

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;
            }
        }
    }
}
like image 288
ZWis212 Avatar asked May 25 '26 04:05

ZWis212


1 Answers

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.

like image 197
bdkosher Avatar answered May 26 '26 17:05

bdkosher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!