1.7k views
2 votes
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, 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.Sample output is as follows:Candidate Names Number Of Votes Recieved Percentage Of The Total Votes RecievedJohnson 5000 25.91Miller 4000 20.72Duffy 6000 31.09Robinson 2500 12.95Sam 1800 9.33Total 19300

User Luiza
by
6.5k points

1 Answer

4 votes

Explanation & Answer:

//written in java

import java.util.*;

public class Election{

public static void main(String[] args) {

String[] candidate = new String[5];

int[] votes = new int[5];

double percent;

int i, sum = 0, highest = 0, winner = 0;

Scanner s = new Scanner(System.in);

//get input

for (i = 0; i < 5; i++) {

System.out.print("Enter last name of Candidate " + (i + 1) + ":");

candidate[i] = s.next();

System.out.print("Enter number of votes received: ");

votes[i] = s.nextInt();

if (votes[i] > highest) {

highest = votes[i];

winner = i;

}//if

sum += votes[i];

System.out.println();

}//for

//generate output

System.out.println("The results are:");

System.out.println("Candidate\tVotes Received\t% of TotalVotes\\");

for (i = 0; i < 5; i++) {

percent = (((float) votes[i]) * 100) / sum;

System.out.println(candidate[i] + "\t\t" + votes[i] + "\t\t\t" + String.format("%.2f",percent));

}//for

System.out.println("\\Total:\t" + sum);

System.out.println("The winner of the Election is: " + candidate[winner]);

}//main

}//Election

User CodingInMyBasement
by
5.8k points