如何用格式化程序格式化和二维数组? [英] how to format the sum two dimensional arrays with formatter?

查看:91
本文介绍了如何用格式化程序格式化和二维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在2维数组上添加2008年选举的每个州的选票,但是当我运行代码时,它只对第一行求和,然后继续将自身与前面的和相加51次,如右图所示:

I have to add the votes per state of the 2008 elections on a 2 dimensional array, but when I run the code it sums only the first row and then keeps adding itself to the previous sum 51 times to the right side like this:


  • 州奥巴马麦凯恩州其他州合计

  • 阿拉巴马州813479 1266546 19794 2099819 2426016 72985等。 ..

  • 阿拉斯加123594 193841 8762 2099819 2426016 72985等...

但是我需要

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][4];  
  int[] Totalbystate = new int[votes.length];  

  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);  
  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 row=0; row < votes.length; row++)  
    {  
      for (int col=0; col < votes[row].length; col++)  
      {  
        sum = sum + votes[row][col];  
      }  
      fmt = new Formatter();  
      fmt.format("%21d", sum);  
      System.out.print(fmt);  
    }  

    System.out.println();  
  }  
}  


推荐答案


,但是当我运行代码时,它只对第一行求和,然后继续将自身与前面的总和相加51次,如下所示:

but when I run the code it sums only the first row and then keeps adding itself to the previous sum 51 times to the right side like this:

查看您的代码:

int sum =0;
for(int row=0; row < votes.length; row++)
{   
    for (int col=0; col < votes[row].length; col++)
    {
        sum = sum + votes[row][col];
    }
    fmt = new Formatter();
    fmt.format("%21d", sum);
    System.out.print(fmt);  
}

看看在哪里设置 sum 设为0。现在考虑您应该在哪里将其设置为0 ...

Look at where you're setting sum to 0. Now think about where you should be setting it to 0...

这篇关于如何用格式化程序格式化和二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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