java 二维数组 组合,如何在Java中求和二维数组的列

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?

WyOxw.png

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

}

}

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]; //

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

Hope this helps!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值