如何使用格式化程序格式化二维数组?

时间:2012-10-09 16:28:24

标签: java arrays multidimensional-array sum

我必须在二维数组中添加2008年选举的每个状态的投票,但是当我运行代码时,它仅对第一行求和,然后继续将自己添加到前一个总和51次,如右边这样:

  • 州奥巴马麦凯恩其他州总计
  • Alabama 813479 1266546 19794 2099819 2426016 72985等......
  • Alaska 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();  
  }  
}  

1 个答案:

答案 0 :(得分:1)

  

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

看看你的代码:

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 ...