投票程序 候选人5人,姓名,编号,票数, 录入候选人信息,键盘录入姓名,按顺序自动产生编号 显示候选人信息 键盘录入候选人编号,给相应的后选人投一票,录入0投票结束 根据票数排序 显示最终结果 用Java 对象数组写
时间: 2024-04-07 11:33:53 浏览: 39
Sure! Here's an example of a voting program in Java using an array of objects:
```java
import java.util.Scanner;
class Candidate {
String name;
int id;
int votes;
public Candidate(String name, int id) {
this.name = name;
this.id = id;
this.votes = 0;
}
}
public class VotingProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of candidates: ");
int numCandidates = scanner.nextInt();
scanner.nextLine();
Candidate[] candidates = new Candidate[numCandidates];
// Input candidate information
for (int i = 0; i < numCandidates; i++) {
System.out.print("Enter candidate name: ");
String name = scanner.nextLine();
// Generating candidate ID based on index
int id = i + 1;
candidates[i] = new Candidate(name, id);
}
// Display candidate information
System.out.println("\nCandidate Information:");
for (Candidate candidate : candidates) {
System.out.println("Name: " + candidate.name);
System.out.println("ID: " + candidate.id);
System.out.println("Votes: " + candidate.votes);
System.out.println();
}
// Voting process
System.out.println("Enter candidate ID to vote (or 0 to end):");
int voteId = scanner.nextInt();
while (voteId != 0) {
for (Candidate candidate : candidates) {
if (candidate.id == voteId) {
candidate.votes++;
break;
}
}
System.out.println("Enter candidate ID to vote (or 0 to end):");
voteId = scanner.nextInt();
}
// Sort candidates based on votes
for (int i = 0; i < numCandidates - 1; i++) {
for (int j = 0; j < numCandidates - i - 1; j++) {
if (candidates[j].votes < candidates[j + 1].votes) {
// Swap candidates
Candidate temp = candidates[j];
candidates[j] = candidates[j + 1];
candidates[j + 1] = temp;
}
}
}
// Display final results
System.out.println("\nFinal Results:");
for (Candidate candidate : candidates) {
System.out.println("Name: " + candidate.name);
System.out.println("ID: " + candidate.id);
System.out.println("Votes: " + candidate.votes);
System.out.println();
}
}
}
```
You can run this code to create a voting program for 5 candidates. The program will prompt you to enter candidate names, generate a unique ID for each candidate, allow you to vote for candidates by entering their ID, and finally display the results sorted by the number of votes.
阅读全文