简体   繁体   中英

how to format the sum two dimensional arrays with formatter?

I have to add the votes per state of the 2008 elections on a 2 dimensional array, but when I run the code it sums only the first row and then keeps adding itself to the previous sum 51 times to the right side like this:

  • State Obama McCain Other Total by state
  • Alabama 813479 1266546 19794 2099819 2426016 72985 etc...
  • Alaska 123594 193841 8762 2099819 2426016 72985 etc...

But i needed to add the total votes on each state only once per row.

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

but when I run the code it sums only the first row and then keeps adding itself to the previous sum 51 times to the right side like this:

Look at your code:

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

Look at where you're setting sum to 0. Now think about where you should be setting it to 0...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM