如何在java中对二维数组的列求和 [英] how to sum the columns of a 2 dimensional array in java

查看:36
本文介绍了如何在java中对二维数组的列求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我正在尝试添加二维数组的列的总和,但到目前为止,我能够添加行的总和,但不能添加其他 3 列.有人可以告诉我我做错了什么吗?

ok, I'm trying to add the the sum of the columns of a two dimensional array but so far i was able to add the total of the sum of the rows but Not the other 3 columns. can someone please show me what I'm doing wrong?

    public static void main(String[] args) throws IOException
{
    // TODO code application logic here
    File election = new File("voting_2008.txt");
    Scanner sc = new Scanner(election);

    String[] states = new String[51];
    int[][]votes = new int[51][3];


    for (int s=0; s < 51; s++)
    {
        states[s] = sc.nextLine();
    }

    for(int c=0; c < 3; c++)
    {
        for(int s=0; s < 51; s++)
        {
            votes[s][c] = sc.nextInt();

        }

    }
    Formatter fmt = new Formatter();
    fmt.format("%20s%12s%12s%12s%21s", "State", "Obama", "McCain", "Other", "Total by state");
    System.out.println(fmt);
    int TotalSum; 
    TotalSum = 0;
    for (int s=0; s < 51; s++)
    {
       fmt = new Formatter();
       fmt.format("%20s", states[s]);
       System.out.print(fmt);
       for(int c=0; c < 3; c++)
       {
           fmt = new Formatter();
           fmt.format("%12d", votes[s][c]);
           System.out.print(fmt);

       }


           int sum =0;
           for (int col=0; col < votes[s].length; col++)
           {
              sum = sum + votes[s][col];

           }

           TotalSum += sum;
           fmt = new Formatter();
            fmt.format("%21d", sum);
            System.out.print(fmt); 



       System.out.println();

    }
    Formatter fmt2 = new Formatter();
    fmt2.format("%20s%12s%12s%12s%21s", "Total", "", "", "", TotalSum);
    System.out.print( fmt2 );
}

}

推荐答案

几个简单的更改即可解决您的问题:

Couple of simple changes to fix your issue:

1> 将前两个 for 循环合并为:

1> Merge the first two for loops as:

    for (int s=0; s < 2; s++){
        states[s] = sc.next();
        for(int c=0; c < 3; c++) {
            votes[s][c] = sc.nextInt();
        }
    }

  1. 在 TotalSum 旁边定义一个新的 colSum[],如下所示:

  1. Define a new colSum[] next to TotalSum as below:

int TotalSum = 0;
int colSum[] = new int[]{0,0,0};

  • 更新投票打印循环以进行列总和:

  • Update vote printing for loop to do the column sum as well:

       for(int c=0; c < 3; c++) {
           colSum[c]+=votes[s][c]; // <-- new line to do the column sum
           fmt = new Formatter();
           fmt.format("%12d", votes[s][c]);
           System.out.print(fmt);
       }
    

  • 将最后一行中的列总和打印为:

  • Print the columns sum in last line as :

        fmt2.format("%20s%12s%12s%12s%21s", "Total", colSum[0], colSum[1], colSum[2], TotalSum);
        System.out.print( fmt2 );
    

  • 希望这有帮助!!

    这篇关于如何在java中对二维数组的列求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆