Help me modify the code below so that the total votes cast per state is shown. I
ID: 3640624 • Letter: H
Question
Help me modify the code below so that the total votes cast per state is shown. In other words, I need to add a column to each row summing the total votes cast for all candidates per state.(Here is a link to the text file I'm using: https://skydrive.live.com/redir.aspx?cid=6a7336f2f22f7dcb&resid=6A7336F2F22F7DCB!127&parid=6A7336F2F22F7DCB!117&authkey=!AEHUTN7Rn78A6VM)
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();
Formatter format = fmt.format("%20s%12s%12s%12s", "State", "Obama",
"McCain","Other");
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);
}
System.out.println();
Explanation / Answer
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.Scanner;
public class Program {
public static void main(String[] args) throws FileNotFoundException {
File election = new File ("voting_2008.txt");
Scanner sc = new Scanner(election);
String[] states = new String[51];
int[][] votes = new int[51][3];
int sum;
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%12s", "State", "Obama", "McCain", "Other", "Total");
System.out.println(fmt);
for(int s = 0; s < 51; s++)
{
fmt = new Formatter();
fmt.format("%20s", states[s]);
System.out.print(fmt);
sum = 0;
for (int c = 0; c < 3; c++)
{
sum += votes[s][c];
fmt = new Formatter();
fmt.format("%12d", votes[s][c]);
System.out.print(fmt);
}
fmt = new Formatter();
fmt.format("%12d", sum);
System.out.print(fmt);
System.out.println();
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.