Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.9 kB
2
Indexable
Never
import java.util.Scanner;

public class Election {
    public static void main(String[] args) {
        String[] candidateNames = new String[5];
        int[] votesReceived = new int[5];
        Scanner scanner = new Scanner(System.in);

        promptUserForInput(scanner, candidateNames, votesReceived);
        printCandidateInformation(candidateNames, votesReceived);
        printElectionResults(candidateNames, votesReceived);
    }

    private static void promptUserForInput(Scanner scanner, String[] candidateNames, int[] votesReceived) {
        for (int i = 0; i < 5; i++) {
            System.out.print("Enter candidate's last name: ");
            candidateNames[i] = scanner.nextLine();

            System.out.print("Enter candidate's votes: ");
            votesReceived[i] = scanner.nextInt();
            scanner.nextLine();
        }
    }

    private static void printCandidateInformation(String[] candidateNames, int[] votesReceived) {
        System.out.printf("%-15s%-15s%-15s\n", "Candidate", "Votes Received", "% of Total Votes");

        int totalVotes = 0;
        for (int i = 0; i < 5; i++) {
            totalVotes += votesReceived[i];
        }

        for (int i = 0; i < 5; i++) {
            double percent = (double) votesReceived[i] / totalVotes * 100;
            System.out.printf("%-15s%-15d%-15.2f\n", candidateNames[i], votesReceived[i], percent);
        }

        System.out.printf("%-15s%-15d\n", "Total", totalVotes);
    }

    private static void printElectionResults(String[] candidateNames, int[] votesReceived) {
        int maxVotesIndex = 0;
        for (int i = 0; i < 5; i++) {
            if (votesReceived[i] > votesReceived[maxVotesIndex]) {
                maxVotesIndex = i;
            }
        }

        System.out.printf("The winner of the election is %s.\n", candidateNames[maxVotesIndex]);
    }
}