2012-10-09 84 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