2012-10-09 83 views
0

我必须在2008年选举的每个州的2维数组上添加选票,但是当我运行代码时,它只汇总第一行,然后不断将自己添加到右侧的前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(); 
    } 
} 

回答

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

+0

真棒我转移到内部循环,现在它的完美添加。然而它不断将总和放在右侧51次,而不是按照状态列总数。你有什么建议吗?谢谢 – UnPatoCuacCuac

+1

@ user1663414:您真的*无法在评论中显示此内容。但是这听起来像现在是一个单独的问题。你需要弄清楚如何区分你的顾虑。 –

+0

好的。谢谢。我将要求againg以正确的总和谢谢。 – UnPatoCuacCuac