ok, I'm trying to add the the sum of the columns of a two dimensional array but so far i was able to add the total of the sum of the rows but Not the other 3 columns. can someone please show me what I'm doing wrong?
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][3];
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);
int TotalSum;
TotalSum = 0;
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 col=0; col < votes[s].length; col++)
{
sum = sum + votes[s][col];
}
TotalSum += sum;
fmt = new Formatter();
fmt.format("%21d", sum);
System.out.print(fmt);
System.out.println();
}
Formatter fmt2 = new Formatter();
fmt2.format("%20s%12s%12s%12s%21s", "Total", "", "", "", TotalSum);
System.out.print( fmt2 );
}
}
解决方案
Couple of simple changes to fix your issue:
1> Merge the first two for loops as:
for (int s=0; s < 2; s++){
states[s] = sc.next();
for(int c=0; c < 3; c++) {
votes[s][c] = sc.nextInt();
}
}
Define a new colSum[] next to TotalSum as below:
int TotalSum = 0;
int colSum[] = new int[]{0,0,0};
Update vote printing for loop to do the column sum as well:
for(int c=0; c < 3; c++) {
colSum[c]+=votes[s][c]; //
fmt = new Formatter();
fmt.format("%12d", votes[s][c]);
System.out.print(fmt);
}
Print the columns sum in last line as :
fmt2.format("%20s%12s%12s%12s%21s", "Total", colSum[0], colSum[1], colSum[2], TotalSum);
System.out.print( fmt2 );
Hope this helps!!