Java 如何使用formatter格式化二维数组和?

Java 如何使用formatter格式化二维数组和?,java,arrays,multidimensional-array,sum,Java,Arrays,Multidimensional Array,Sum,我必须在二维数组中添加2008年选举的每个州的投票数,但当我运行代码时,它只对第一行进行求和,然后在右侧将其自身与前一行求和51次,如下所示: 按州分列的其他总数 阿拉巴马州813479 1266546 19794 2099819 2426016 72985等 阿拉斯加123594 193841 8762 2099819 2426016 72985等 但我只需要在每一行中添加每个州的总投票数一次 public static void main(String[] args) throws IO

我必须在二维数组中添加2008年选举的每个州的投票数,但当我运行代码时,它只对第一行进行求和,然后在右侧将其自身与前一行求和51次,如下所示:

  • 按州分列的其他总数
  • 阿拉巴马州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();  
  }  
}  
publicstaticvoidmain(字符串[]args)引发IOException
{  
//此处的TODO代码应用程序逻辑
文件选择=新文件(“voting_2008.txt”);
扫描仪sc=新扫描仪(选择);
字符串[]状态=新字符串[51];
int[][]票=新int[51][4];
int[]Totalbystate=新的int[vots.length];
对于(int s=0;s<51;s++)
{  
states[s]=sc.nextLine();
}  
对于(int c=0;c<3;c++)
{  
对于(int s=0;s<51;s++)
{  
票数[s][c]=sc.nextInt();
}  
}  
格式化程序fmt=新格式化程序();
格式(“%20s%12s%12s%12s%21s”、“州”、“奥巴马”、“麦凯恩”、“其他”、“各州合计”);
系统输出打印项次(fmt);
对于(int s=0;s<51;s++)
{  
fmt=新格式化程序();
格式(“%20s”,表示[s]);
系统输出打印(fmt);
对于(int c=0;c<3;c++)
{  
fmt=新格式化程序();
格式(“%12d”,投票[s][c]);
系统输出打印(fmt);
}  
整数和=0;
for(int row=0;row
但是,当我运行代码时,它只对第一行求和,然后将自己与前面的求和相加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);  
}
int和=0;
for(int row=0;row

查看将
sum
设置为0的位置。现在想想应该在哪里将其设置为0…

太棒了,我移动到了内部循环,现在它添加得非常完美。然而,它不断地把总数放在右边51次,而不是按州分列在总数栏下。你对此有什么建议吗?Thanks@user1663414:你真的无法在评论中显示这一点。但这听起来像是一个单独的问题。你需要找出如何区分你的顾虑。好的。非常感谢。我要用正确的总结问阿甘,谢谢。