Short Java Program Question... Please fill out the code: public class ElectionRe
ID: 3793657 • Letter: S
Question
Short Java Program Question...
Please fill out the code:
public class ElectionResuls {
The Galaxers have stored the votes from the election in a file (called votes.txt), but need some help tabulating them. The lines in their file look like this: g1*q! g4 w# g3* times @ g2*z? g4*w# g4*w# g2*z? g1*q! Happy to oblige, you whip up a Java program that uses the following methods: public static int []countVotes (Scanner s) public static void printVotes (int [] v) to tally and print out the counts like this: g1*q! g2*z? g3* times @ g4*w# 2891 4287 2272 3264Explanation / Answer
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class VoteTest {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("D:\votes.txt");
Scanner scanner = new Scanner(file);
int[] votes = countVotes(scanner);
printVotes(votes);
}
private static void printVotes(int[] votes) {
for (int vote : votes) {
if (vote != 0) {
System.out.println("the votes are " + vote);
}
}
}
private static int[] countVotes(Scanner scanner) {
String line = null;
int[] array = new int[10];
int count = 0;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
String[] words = line.split("\s+");// to divide the words based on
// spaces
for (String word : words) {
if (word.trim().equals("g1*q!")) {
array[count] = 2891;
count++;
}
if (word.trim().equals("g2*z?")) {
array[count] = 4287;
count++;
}
if (word.trim().equals("g3*x@")) {
array[count] = 2272;
count++;
}
if (word.trim().equals("g4*w#")) {
array[count] = 3264;
count++;
}
}
output
the votes are 2891
the votes are 4287
the votes are 2272
the votes are 3264
the votes are 2891
the votes are 4287
the votes are 2272
the votes are 3264
votes.txt
g1*q! g2*z? g3*x@ g4*w# g1*q! g2*z? g3*x@ g4*w#
}
return array;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.