JAVA,面向对象写一个投票程序
时间: 2023-05-31 12:06:13 浏览: 87
以下是一个基本的投票程序:
```java
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class VoteProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Map<String, Candidate> candidates = new HashMap<>();
int numCandidates = 0;
System.out.println("Welcome to the voting program!");
System.out.print("Enter the number of candidates: ");
numCandidates = scanner.nextInt();
scanner.nextLine(); // consume the newline character
for (int i = 1; i <= numCandidates; i++) {
System.out.print("Enter the name of candidate #" + i + ": ");
String name = scanner.nextLine();
candidates.put(name, new Candidate(name));
}
while (true) {
System.out.println("Please select an option:");
System.out.println("1. Vote");
System.out.println("2. View Results");
System.out.println("3. Exit");
int choice = scanner.nextInt();
scanner.nextLine(); // consume the newline character
if (choice == 1) {
System.out.print("Enter the name of the candidate you want to vote for: ");
String candidateName = scanner.nextLine();
Candidate candidate = candidates.get(candidateName);
if (candidate == null) {
System.out.println("Invalid candidate name.");
} else {
candidate.addVote();
System.out.println("You have successfully voted for " + candidate.getName() + ".");
}
} else if (choice == 2) {
System.out.println("Current vote count:");
for (Candidate candidate : candidates.values()) {
System.out.println(candidate.getName() + ": " + candidate.getVoteCount());
}
} else if (choice == 3) {
System.out.println("Thank you for using the voting program!");
break;
} else {
System.out.println("Invalid choice.");
}
}
}
}
class Candidate {
private String name;
private int voteCount;
public Candidate(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int getVoteCount() {
return voteCount;
}
public void addVote() {
voteCount++;
}
}
```
这个程序使用了一个 `Map` 来存储候选人的信息,其中每个候选人都对应一个 `Candidate` 对象。`Candidate` 类包含了候选人的姓名和票数,以及相关的 getter 和 setter 方法。程序的主要逻辑是一个循环,其中用户可以选择投票、查看结果或退出程序。在投票过程中,程序会验证用户输入的候选人姓名是否有效,并更新对应候选人的票数。在查看结果时,程序会遍历 `Map` 中的所有候选人,并输出他们的姓名和票数。
阅读全文