CAN SOMEONE HELP ANSWER THIS QUESTION PLEASE
Write a program that allows the user to enter the last names of five candidates in a local election and the votes received by each candidate. The program should then output each candidate?s name, the votes received by that candidate and the percentage of the total votes received by the candidate. Your program should also output the winner of the election.
A sample output is:
Candidate Votes Received % of Total Votes
Johnson 5000 25.91
Miller 4000 20.72
Duffy 6000 31.09
Robinson 2500 12.95
Murphy 1800 9.33
Total 19300
The winner of the election is Duffy
Hint: use parallel arrays
Here is an example that allows the user to enter the last names of five candidates in a local election and the votes received by each candidate. The program will display the winner of the election with no of votes received.
import java.util.*; import java.text.*; class Candidate{ public String lname; public int vote; public Candidate(String lname,int vote) { super(); this.lname = lname; this.vote=vote; } public String getLname() { return lname; } public int getVote(){ return vote; } } class VoteComparator implements Comparator{ public int compare(Object can1, Object can2){ int v1 = ((Candidate)can1).getVote(); int v2 = ((Candidate)can2).getVote(); if(v1 > v2) return 1; else if(v1 < v2) return -1; else return 0; } } class VotesOfCandidates { public static void main(String[] args) { int total=0; List<Candidate> list = new ArrayList<Candidate>(); Scanner input=new Scanner(System.in); for(int i=0;i<5;i++){ System.out.print("Enter Last Name: "); String lname=input.next(); System.out.print("Enter no of votes: "); int votes=input.nextInt(); list.add(new Candidate(lname,votes)); total+=votes; } DecimalFormat df=new DecimalFormat("##.##"); System.out.println("Total votes: "+total); for(Candidate data: list){ int v=data.getVote(); double p=(double)v/total; double per=p*100; System.out.println(data.getLname()+"\t"+data.getVote()+"\t"+df.format(per)); } int v=0; Collections.sort(list,new VoteComparator()); for(Candidate data: list){ v=data.getVote(); } String can=""; System.out.println("Highest Vote is: "+v); for(Candidate data: list){ if(v==data.getVote()){ can=data.getLname(); } } System.out.println(can+" won the election with "+v+" votes"); } }
Ads