如何从二维数组的列总和中查找数组的最大值

时间:2015-04-20 01:04:08

标签: java arrays

找到行的最大值的第一个数组工作正常,但由于某种原因,列总和的数组列出了完全在列数组之和的元素之外的其他内容。

import java.util.*;

public class Quiz 
{
    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);
        Scanner input2 = new Scanner(System.in);

        System.out.println("Please eneter 20 numbers");

        int userinput[][] = new int[4][5];

        String StringInput;

        for(int column = 0; column < 4; column++)
        {
            for(int row = 0; row < 5; row++)
            {
                userinput[column][row] = input.nextInt();
            }
        }

        for(int column = 0; column < 4; column++)
        {
            for(int row = 0; row < 5; row++)
            {
                System.out.print(userinput[column][row] + " ");
            }
            System.out.println();
        }


        int[] sumOfRows = new int[userinput.length]; 

        int sumR = 0; 

        int largetstrow = sumOfRows[0];

        for(int row = 0; row < userinput.length; row++)
        { 
            for(int col = 0; col < userinput[0].length; col++)
            { 
                sumR += userinput[row][col]; 
            } 
            sumOfRows[row] = sumR; 
            sumR = 0; 

            if(sumOfRows[row] > largetstrow)
                largetstrow = sumOfRows[row];
        } 
        System.out.println("The sum of each rows are " + Arrays.toString(sumOfRows)); 
        System.out.println(largetstrow);


        int size = userinput[0].length;
        int sumOfColumn[] = new int[size]; // used for columns addition

        int largestColumn = sumOfColumn[0];

        int highestSumC = 0; 
        int highestIndexC = 0; 
        for (int i = 0; i < userinput.length; i++)
        {
            for (int j = 0; j < userinput[i].length; j++)
            {
                sumOfColumn[j] += userinput[i][j];
                if(sumOfColumn[i] > highestSumC)
                { 
                    highestSumC = sumOfColumn[i]; 
                    highestIndexC = i; 
                } 
            }
        }

        System.out.println("The sum of each columns are " + Arrays.toString(sumOfColumn));


        System.out.println(highestSumC);
    }
}

1 个答案:

答案 0 :(得分:0)

        // it's j
        sumOfColumn[j] += userinput[i][j];

        // it's i
        if(sumOfColumn[i] > highestSumC)
        { 
            highestSumC = sumOfColumn[i]; 
            highestIndexC = i; 
        } 

为什么要从j切换到i?

如果你颠倒循环并将列循环作为外部并将行作为内部循环,那么这可能会更容易,那么你几乎可以像第一个那样执行它,而不是必须拥有中间数组以保持运行总量。

此外,放弃ij作为变量名称,支持rowcol,以帮助您了解正在进行的操作。