2012-10-09 166 views
0

我想添加每个状态的投票总数和这个二维数组的每个候选人的总和。总和二维阵列

这些要求:

  • 修改,使每个州的总投票数显示
    (即程序,添加一列,以每列投给每个州的所有 候选人总票数相加)
  • 修改程序,使每个候选人的总票数显示(即,添加最后一行显示了票的所有三列)

    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", Totalbystate) ; 
        System.out.println(); 
    } 
    
  • 获得总票数
+1

嗯..那么,这是什么问题? –

+2

是的,**你**是。 –

+0

总和不起作用。当我编译时,我得到一个错误 异常在线程“主”java.util.IllegalFormatConversionException:d!= [I 阿拉巴马州813479 1266546 19794 \t在java.util.Formatter $ FormatSpecifier.failConversion(Formatter.java:4045) \t在$的java.util.Formatter FormatSpecifier.printInteger(Formatter.java:2748) \t在$的java.util.Formatter FormatSpecifier.print(Formatter.java:2702) \t在java.util.Formatter.format(格式化。的java:2488) \t在java.util.Formatter.format(Formatter.java:2423) \t在small_program_07.Small_program_07.main(Small_program_07.java:69) Java结果:1 – UnPatoCuacCuac

回答

6

该问题与求和无关,以及与格式有关的所有问题。只是代码将表现出同样的问题:

int[] values = new int[10]; 
new Formatter().format("%21d", values); 

目前尚不清楚你希望这个做什么,但我怀疑你实际上想要么做这样的事情:

// Please change your variable names to follow Java conventions 
fmt = new Formatter(System.out); 
for (int value : Totalbystate) { 
    fmt.format("%21d", value); 
} 

或者,请指定单个格式字符串,例如"%21d%21d%21d%21d%21d"(etc)并传入Integer[]而不是int[]

此外,你应该修复你的程序的缩进 - 这是目前不必要的混淆。