First of all, your loops will print "the matrix is asymmetric \ n" whenever they find i and j for which matrix[i][j] != matrix[j][i] , which can happen more than once.
and System.out.print("matrix is symmetric \n"); always called, therefore explains the last line of output.
You probably want your method to have a boolean return value instead of printing this output. Thus, loops will only be repeated until you know that the matrix is not symmetrical.
public boolean isSymmetricNow(int[][] matrix){ //Random random = new Random(); for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix.length; j++) { //matrix[i][j] = random.nextInt(20); if (matrix[i][j] != matrix[j][i]) { return false; } } } return true; }
To do the same without returning value:
public void isSymmetricNow(int[][] matrix){ //Random random = new Random(); boolean isSymmetric = true; for (int i = 0; i < matrix.length && isSymmetric; i++) { for (int j = 0; j < matrix.length && isSymmetric; j++) { //matrix[i][j] = random.nextInt(20); if (matrix[i][j] != matrix[j][i]) { System.out.print("matrix is not symmetric \n"); isSymmetric = false; } } } if (isSymmetric) System.out.print("matrix is symmetric \n"); }
source share