In: Computer Science
Write a java program using the following instructions:
Write a program that determines election results. Create two parallel arrays to store the last names of five candidates in a local election and the votes received by each candidate. Prompt the user to input these values. The program should output each candidates name, the votes received by that candidate, the percentage of the total votes received by the candidate, and the total votes cast. Your program should also output the winner of the election. To do this, write the following method: findHighest which receives an array of int. It determine the highest value in the array and returns the location of that value. Call this method to determine the location of the highest value in your votes array, and use this to display the winner from the names array.
SAMPLE OUTPUT:
Enter candidate name: Johnson
Enter votes received: 5000
Enter candidate name: Miller
Enter votes received: 4000
Enter candidate name: Duffy
Enter votes received: 6000
Enter candidate name: Robinson
Enter votes received: 2500
Enter candidate name: Ashton
Enter votes received: 1800
Candidate Votes Received % of Total
Johnson 5000 25.91
Miller 4000 20.72
Duffy 6000 31.09
Robinson 2500 12.95
Ashton 1800 9.33
Total votes: 19300
The winner of the election is Duffy.
Please give a thumbsup, if this is helpful for you!!
import java.util.Scanner;
import java.text.DecimalFormat;
public class Election_results {
public static int findHighest(int[] arr){
int max=0,pos=-1;
for(int
i=0;i<arr.length;i++){
if(arr[i]>max){
max=arr[i];
pos=i;
}
}
return pos;
}
public static void main(String []args ){
int loc;
double temp;
Scanner sc = new
Scanner(System.in);
System.out.print("Enter the length
of the array: ");
int n=sc.nextInt();
String arr1[]=new String[n];
int arr2[]=new int[n];
for(int i=0;i<n;i++){
System.out.print("Enter candidate name: ");
arr1[i]=sc.next();
System.out.print("Enter votes received: ");
arr2[i]=sc.nextInt();
}
int total=0;
for(int i=0;i<n;i++){
total+=arr2[i];
}
DecimalFormat df = new
DecimalFormat("##.##");
System.out.print("\n\nCandidate\tVotes Received\t% of
Total\n");
for(int i=0;i<n;i++){
temp=
((double)arr2[i]/(double)total)*100;
System.out.print(arr1[i]+"\t\t"+arr2[i]+"\t\t"+df.format(temp)
+"\n");
}
System.out.print("\n\nTotal votes:
"+total);
loc=findHighest(arr2);
System.out.print("\nThe winner of
the election is "+arr1[loc]+".");
sc.close();
}
}
Output: