用Java编写通过任务描述可知,需要定义一个参与投票的学生类Voter类,它具有姓名,最大投票数,当前投票总数,和投票意见。 (2)因为所有参与投票的学生都会改变同一个数据,即投票次数,一次把它定义成静态变量:private static int count; (3)另外,为了防止学生重复投票,必须保存参与投票的学生信息,可采用一个集合来存放已经投票的学生对象。 private static Set<Voter> voters = new HashSet<Voter>(); (4)最后编写测试Voter类的投票和打印投票结果功能。
时间: 2023-06-24 19:05:29 浏览: 84
下面是Java代码实现:
```
import java.util.HashSet;
import java.util.Set;
public class Voter {
private String name;
private int maxVotes;
private int currentVotes;
private String vote;
private static int count;
private static Set<Voter> voters = new HashSet<Voter>();
public Voter(String name, int maxVotes) {
this.name = name;
this.maxVotes = maxVotes;
this.currentVotes = 0;
this.vote = "";
}
public void vote(String option) {
if (currentVotes < maxVotes && !voters.contains(this)) {
currentVotes++;
vote += option + " ";
voters.add(this);
count++;
}
}
public static int getCount() {
return count;
}
public static void printResult() {
System.out.println("投票总人数:" + voters.size());
System.out.println("总投票数:" + count);
System.out.println("投票结果:");
for (Voter voter : voters) {
System.out.println(voter.name + ":" + voter.vote);
}
}
}
```
使用示例:
```
public static void main(String[] args) {
Voter v1 = new Voter("张三", 3);
Voter v2 = new Voter("李四", 2);
Voter v3 = new Voter("王五", 1);
v1.vote("选项A");
v1.vote("选项B");
v1.vote("选项C");
v1.vote("选项A"); // 重复投票无效
v2.vote("选项B");
v2.vote("选项C");
v2.vote("选项C"); // 重复投票无效
v3.vote("选项A");
Voter.printResult();
}
```