I have to add the sum of the rows of a two dimensional array in a column to the right side. however, when I run the code it adds the sum of all the rows in every column until it reaches the end. like this: https://i.stack.imgur.com/1QQZT.png the sum is right but is suppose to go down and just 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);
}
for(int row=0; row < votes.length; row++)
{
int sum =0;
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();
}
}
}
Try using : –
System.out.println(fmt);in place of commented code..UPDATE :- Don’t do the above change.. Will not work.. Do the following change indeed.
Here’s is the problem.. You’re printing your
total no of votes, 51 * 51 times.. You’re having this loop inside another loop, which is already running 51 times..So, to solve your problem.. Remove the outer loop from the above code, and just keep it like this: –
Value of
syou are getting from the outer-most loop ..UPDATE: – In case you want sum of all the votes.. For all column..