用java写voting
时间: 2024-03-08 14:50:55 浏览: 111
以下是一个简单的使用Java实现投票的示例程序:
```java
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class VotingSystem {
public static void main(String[] args) {
Map<String, Integer> candidates = new HashMap<String, Integer>();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of candidates: ");
int numCandidates = scanner.nextInt();
scanner.nextLine(); // consume the newline character left by nextInt()
for (int i = 1; i <= numCandidates; i++) {
System.out.print("Enter the name of candidate " + i + ": ");
String name = scanner.nextLine();
candidates.put(name, 0);
}
while (true) {
System.out.print("Enter your vote (or 'done' to finish voting): ");
String vote = scanner.nextLine();
if (vote.equals("done")) {
break;
}
if (!candidates.containsKey(vote)) {
System.out.println("Invalid vote.");
} else {
candidates.put(vote, candidates.get(vote) + 1);
}
}
int maxVotes = 0;
String winner = "";
for (String candidate : candidates.keySet()) {
int votes = candidates.get(candidate);
if (votes > maxVotes) {
maxVotes = votes;
winner = candidate;
}
System.out.println(candidate + ": " + votes + " votes");
}
System.out.println("Winner: " + winner);
}
}
```
此程序首先要求输入候选人的数量和姓名,然后要求逐个输入投票,直到输入“done”为止。程序会在每次投票后更新每个候选人的票数,并在投票结束后输出每个候选人的票数和最终获胜者的姓名。
请注意,此程序仅用于演示目的,并不具备安全性和可扩展性。在实际应用中,需要考虑更多的因素,例如选民身份验证、防止重复投票等。
阅读全文