In Java Write a method that allows the user to enter the las
In Java
Write a method 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 would be:
Candidate Votes Received % of Total Votes
Johnson 5000 25.91
Miller 4000 20.73
Wilson 6000 31.09
Robinson 2500 12.95
Abbot 1800 9.33
Total 19300
The winner of the election is Wilson
Make a method \"calculateElection\"
Solution
VotesPercentage.java
import java.util.Scanner;
public class VotesPercentage {
public static void main(String[] args) {
//Creating two arrays which is of size 5
int votes[]=new int[5];
String names[]=new String[5];
int total=0;
//Scanner object is used to get the inputs entered by the user
Scanner sc=new Scanner(System.in);
System.out.println(\"Enter candidate\'s name and the votes received by the candidate.\");
/* This for loop will get each candidate name
* and votes and populate them into an array
*/
for(int i=0;i<5;i++)
{
/* Getting the candidate name
* and votes entered by the user
*/
System.out.print(\"Enter Lastname of candidate \"+(i+1)+\": \");
names[i]=sc.next();
System.out.print(\"Enter no of votes received :\");
votes[i]=sc.nextInt();
total+=votes[i];
}
//Calling the method by passing the inputs as arguments to this method
calculateElection(names,votes,total);
}
/* This method will calculate the total votes polled
* and find the winner based on votes received by each person
*/
private static void calculateElection(String[] names, int[] votes, int total) {
//Declaring the varriables
int winner;
String winner_name = null;
winner=votes[0];
//This for loop will decides the winner based on the votes
for(int j=0;j<5;j++)
{
if(votes[j]>winner)
{
winner=votes[j];
winner_name=names[j];
}
}
//Displaying the result in the tabular form.
System.out.println(\"Candidate\\tVotes Received\\t% of Total Votes\");
for(int i=0;i<5;i++)
{
System.out.printf(\"%10s\\t%s\\t\\t%.2f\ \",names[i],votes[i],((double)votes[i]/total)*100);
}
System.out.println(\"The Winner of the Election is \"+winner_name);
}
}
______________________
output:
Enter candidate\'s name and the votes received by the candidate.
Enter Lastname of candidate 1: Johnson
Enter no of votes received :5000
Enter Lastname of candidate 2: Miller
Enter no of votes received :4000
Enter Lastname of candidate 3: Wilson
Enter no of votes received :6000
Enter Lastname of candidate 4: Robinson
Enter no of votes received :2500
Enter Lastname of candidate 5: Abbot
Enter no of votes received :1800
Candidate Votes Received % of Total Votes
Johnson 5000 25.91
Miller 4000 20.73
Wilson 6000 31.09
Robinson 2500 12.95
Abbot 1800 9.33
The Winner of the Election is Wilson
_______________Thank You

