有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何比较各行的总和?

我已经成功地编写了将一行中的数字相加的代码,但现在我只能比较不同行的总和。什么样的代码比较数组行的和

我曾想过尝试一个if语句,但一旦我得到它,我不知道如何得到不同的行,然后进行比较,因为你不能真正做sum>;总数

public class MatrixLab {

    public int largestRowSum(int[][] matrix) {
        //Comment outline before coding!  
        int[][] nums = matrix;
        int sum = 0;
        int arraySum = 0;
        //add individual rows
        for(int r = 0; r < matrix.length; r++) {
           for(int c = 0; c < matrix[r].length; c++) {
              sum += nums[r][c];
           }
        }
        System.out.println( sum );
        //compare rows 

        //return the value
        System.out.println( arraySum );
    }

它需要在比较行之后返回具有最大值和的行的索引


共 (2) 个答案

  1. # 1 楼答案

    class Matrix
    {
        public static void main(String arg[])
        {
            int[][] num = {{1,4,7},{12,5,56},{2,5,8},{3,6,9}};
            int index = new Matrix().Sum(num);
            System.out.println(""+index+" is index of the row with greatest sum.");
        }
    
        public int Sum(int[][] mat)
        {
            int val = 0,index=0;
            for(int i = 0;i<mat.length;i++)
            {
                int sum = 0;
                for(int j = 0; j<mat[i].length;j++)
                sum += mat[i][j];
                val = (i == 0 ? sum : val);
                if(val < sum)
                {
                    val = sum;
                    index = i;
                }
             }
             return index;
         }
    }
    

    希望这会有所帮助

  2. # 2 楼答案

    保留一个变量,指示到目前为止最大的和,如果你想存储索引

     public int largestRowSum(int[][] matrix) {
        //Comment outline before coding!  
        int[][] nums = matrix;
        int sum = 0;
        int arraySum = 0;
        int maxSum = 0; // Indicates the max sum of row encountered till now
        int indexOfmaxSumRow = 0; // index of row which corresponds to maxsum
        //add individual rows
        for (int r = 0; r < matrix.length; r++) {
            for (int c = 0; c < matrix[r].length; c++) {
                sum += nums[r][c];
            }
            if (sum > maxSum) {
                maxSum = sum;
                indexOfmaxSumRow = r;
            }
        }
        System.out.println(sum);
        //compare rows 
    
        //return the value
        System.out.println(arraySum);
        return indexOfmaxSumRow;
    }