Reputation: 345
I'm suppose to add the sum of the votes per state and the sum per candidate of this two dimensional array.
These are the requirements:
Modify the program so that the total votes per candidate are shown (I.e., add a last row showing total votes received for all three columns of votes)
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();
}
Upvotes: 0
Views: 1213
Reputation: 1499750
The problem has nothing to do with summation, and everything to do with formatting. Just this code will demonstrate the same problem:
int[] values = new int[10];
new Formatter().format("%21d", values);
It's not clear what you expected this to do, but I suspect you actually want to either do something like:
// Please change your variable names to follow Java conventions
fmt = new Formatter(System.out);
for (int value : Totalbystate) {
fmt.format("%21d", value);
}
Alternatively, specify a single format string such as "%21d%21d%21d%21d%21d"
(etc) and pass in an Integer[]
instead of an int[]
.
Additionally, you should fix your program's indentation - it's unnecessarily confusing at the moment.
Upvotes: 6