【问题标题】:Sum Two Dimensional Arrays对二维数组求和
【发布时间】:2012-10-09 05:38:23
【问题描述】:

我想把每个州的投票总和加上这个二维数组的每个候选人的总和。

这些是要求:

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

    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();
    }
    

【问题讨论】:

  • 嗯.. 那么,问题是什么?
  • 总和不起作用。当我编译时,我在线程“main”java.util.IllegalFormatConversionException 中得到一个错误异常:d != [I Alabama 813479 1266546 19794 at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4045) at java.util .Formatter$FormatSpecifier.printInteger(Formatter.java:2748) 在 java.util.Formatter$FormatSpecifier.print(Formatter.java:2702) 在 java.util.Formatter.format(Formatter.java:2488) 在 java.util。 Formatter.format(Formatter.java:2423) at small_program_07.Small_program_07.main(Small_program_07.java:69) Java 结果:1
  • @user1663414:看看异常到底是怎么说的。它与求和本身无关。

标签: java arrays multidimensional-array


【解决方案1】:

问题与求和无关,与格式有关。只是这个代码将演示同样的问题:

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"(等)并传入 Integer[] 而不是 int[]

此外,您应该修复程序的缩进 - 目前它会造成不必要的混乱。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    • 2013-04-10
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    相关资源
    最近更新 更多