gpt4 book ai didi

java - java中如何对二维数组的列求和

转载 作者:行者123 更新时间:2023-12-01 15:06:40 26 4
gpt4 key购买 nike

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

here is  picture of my output

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

}

最佳答案

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

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

    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[],如下所示:

    int TotalSum = 0;
    int colSum[] = new int[]{0,0,0};
  2. 更新循环的投票打印以执行列总和:

       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);
    }
  3. 将最后一行的列总和打印为:

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

希望这有帮助!!

关于java - java中如何对二维数组的列求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12869878/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com