Home > Net >  Why does Java just skip the loops in this code?
Why does Java just skip the loops in this code?

Time:10-20

I provided a code snippet below.

`

public static void main(String[] args) throws Exception {


    int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};


    System.out.println(hasSymmetry(matrix)); // returns true, so the isComputable condition is verified and the code not executed. Otherwise, it would return false. 
   

}


public static boolean hasSymmetry(int[][] matrix){
    
    // isComputable is defined somewhere else, and it works as expected. 

    if(!isComputable(matrix)){    
        return false;
    }
    

    int length = matrix.length;

    // the loops are skipped without any error. I added the print statements for checking, but they simply don't happen. 

    for (int i = 0; i == length; i  ){
        System.out.println("Inside loop"   i);
        for (int j = 0; j == length; j  ){
            if (matrix[i][j] != matrix[j][i]) {
                System.out.println(matrix[i][j]   " vs "   matrix[j][i]);
                return false;
            }                
        }
    }
    return true;
}

} `

Anyone has an idea why the loops are skipped?

  • I tried making the conditions inside the loop to be i - 2 and j - 2, but it doesn't work.

CodePudding user response:

for (int i = 0; i == length; i  ){
                  ^^
...
    for (int j = 0; j == length; j  ){
                      ^^

There is a mistake in the termination conditions of your for loops.

  • Related