Untitled
unknown
plain_text
2 years ago
1.5 kB
2
Indexable
import java.util.Scanner; public class Election { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String[] candidateNames = new String[5]; int[] votesReceived = new int[5]; // prompt user to enter candidate names and votes received 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(); } int totalVotes = 0; int maxVotesIndex = 0; // calculate total votes and determine the winner for (int i = 0; i < 5; i++) { totalVotes += votesReceived[i]; if (votesReceived[i] > votesReceived[maxVotesIndex]) { maxVotesIndex = i; } } // print candidate information System.out.printf("%-15s%-15s%-15s\n", "Candidate", "Votes Received", "% of Total Votes"); 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); } // print total votes and winner System.out.printf("%-15s%-15d\n", "Total", totalVotes); System.out.printf("The winner of the election is %s.\n", candidateNames[maxVotesIndex]); } }
Editor is loading...