用JAVA面对对象的知识,写一个选班长的投票系统
时间: 2023-06-01 07:03:55 浏览: 95
以下是一个用Java面向对象的投票系统,用于选举班长:
1. 创建一个名为Candidate的类,该类包含候选人的姓名、年龄、性别和得票数。
```
public class Candidate {
private String name;
private int age;
private String gender;
private int voteCount;
public Candidate(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
this.voteCount = 0;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getGender() {
return gender;
}
public int getVoteCount() {
return voteCount;
}
public void addVote() {
voteCount++;
}
}
```
2. 创建一个名为VotingSystem的类,该类包含候选人列表和投票方法。
```
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class VotingSystem {
private List<Candidate> candidates;
private Map<String, Candidate> candidateMap;
public VotingSystem() {
candidates = new ArrayList<Candidate>();
candidateMap = new HashMap<String, Candidate>();
}
public void addCandidate(Candidate candidate) {
candidates.add(candidate);
candidateMap.put(candidate.getName(), candidate);
}
public void vote(String candidateName) {
if (candidateMap.containsKey(candidateName)) {
Candidate candidate = candidateMap.get(candidateName);
candidate.addVote();
} else {
System.out.println("Candidate not found: " + candidateName);
}
}
public Candidate getWinner() {
Candidate winner = null;
for (Candidate candidate : candidates) {
if (winner == null || candidate.getVoteCount() > winner.getVoteCount()) {
winner = candidate;
}
}
return winner;
}
}
```
3. 在主方法中,创建一个VotingSystem对象,并添加候选人。然后,让用户输入投票结果,并将结果记录在VotingSystem对象中。最后,输出获胜者的姓名。
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
VotingSystem system = new VotingSystem();
Candidate candidate1 = new Candidate("Tom", 18, "Male");
Candidate candidate2 = new Candidate("Jane", 17, "Female");
Candidate candidate3 = new Candidate("David", 19, "Male");
system.addCandidate(candidate1);
system.addCandidate(candidate2);
system.addCandidate(candidate3);
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter candidate name to vote (or 'exit' to quit): ");
String input = scanner.nextLine();
if (input.equals("exit")) {
break;
}
system.vote(input);
}
Candidate winner = system.getWinner();
System.out.println("Winner: " + winner.getName());
}
}
```
这个投票系统可以扩展以包含更多功能,例如记录每个投票者的选择,或者限制每个投票者只能投一票。
阅读全文