Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Void method printing two times

Tags:

java

Hello I am trying to understand the code I have written and why does it print the output below

public void isSymmetricNow(int[][] matrix){
    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix.length; j++) {
            if (matrix[i][j] != matrix[j][i]) {
                System.out.print("matrix is not symmetric \n");
            }
        }
    }
    System.out.print("matrix is symmetric \n");
}

prints me

matrix is not symmetric 
matrix is not symmetric 
matrix is symmetric 

ASSUME THAT the given matrix is not symmetric here.

int matrix3[][] = {{1,4,7},{-4,6,6},{7,6,9}};

How can I modify this code to give me back saying if the matrix is symmetric or not only once.

like image 411
Maddy Avatar asked Jul 07 '15 06:07

Maddy


1 Answers

Just a plain return statement will do. It will not execute again if the condition is false.

public void 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]) {
                System.out.print("matrix is not symmetric \n");
                return;
            }
        }
    }
    System.out.print("matrix is symmetric \n");
}

Or

You could return a boolean saying it is a Symmetric or not.

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

then call it using your function.

if(isSymmetric(matrix))
    System.out.println("Symmetric");
else
    System.out.println("Not Symmetric");
like image 181
Uma Kanth Avatar answered Sep 20 '22 16:09

Uma Kanth