Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does Java just skip the loops in this code?

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;
}

}
`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading