简体   繁体   中英

2 dimensional arrays for loops statements java programming

I am trying to write a for statement that sums up the rows and columns of a 2 dimensional array one at a time, and determines if all the sums are the same. I have done the following, and I can't figure out what I am doing wrong.

 public static int isMagic(int mat[][])
    {
        int row = mat.length;
        int col = mat[0].length;
        int sum = row + col;
        if(row == col)
        {
            System.out.println("The matrix is a magic square.");
        }
        else
        {
            System.out.println("The matrix is not a magic square.");
        }
        return sum;
        for(int sumR = 0; sumR < mat.length; sumR++)
        {
            int total = 0;
            for(int sumC = 0; sumC < mat[sumR].length; sumC++)
            {
                total += mat[sumR][sumC];
                if(sumR == 34 && sumC == 34)
                {
                    System.out.println("The sum of all rows and columns is 34.");
                }
                else
                {
                    System.out.println("The matrix is not a magic square.");
                }
            }
            return total;
        }
    }

example of the matrix.

1 2 3 4 5 6 7 8 9

You always return the the variable sum (row + col), it never reaches the loops. Just remove the first return statement and it should work.

I don't recommend that you use your sum variable as your index. Maybe do something like this:

    for(int r = 0; r < mat.length; r++){
      for(int c = 0; c < mat.length; c++){
        sumC = sumC + mat[r][c];
      }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM