2024-10-13 20:28:47 +08:00

96 lines
2.5 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package chapter3.demo34;
/**
* Voter类代表一个投票者
*/
public class Voter {
// 最大投票人数
private static final int MAX_COUNT = 50;
// 当前投票人数
private static int count = 0;
// 存储所有投票者的数组
private static Voter[] voters = new Voter[MAX_COUNT];
// 投票者姓名
private String name;
// 投票意见true表示赞同false表示反对
private boolean opinion;
/**
* 构造方法
* @param name 投票者姓名
*/
public Voter(String name) {
this.name = name;
}
/**
* 投票方法
* @param opinion 投票意见
*/
public void vote(boolean opinion) {
// 检查是否达到最大投票人数
if (count >= MAX_COUNT) {
System.out.println("投票已结束,已达到最大投票数。");
return;
}
// 检查是否重复投票
if (hasVoted(this.name)) {
System.out.println(name + ",请勿重复投票。");
return;
}
// 记录投票意见
this.opinion = opinion;
voters[count] = this;
count++;
System.out.println(name + ",感谢您的投票。");
}
/**
* 检查指定姓名的人是否已经投票
* @param name 要检查的姓名
* @return 如果已投票返回true否则返回false
*/
private static boolean hasVoted(String name) {
for (int i = 0; i < count; i++) {
if (voters[i].name.equals(name)) {
return true;
}
}
return false;
}
/**
* 打印投票结果
*/
public static void printResults() {
System.out.println("===========投票结果===========");
System.out.println("总投票数:" + count);
int agreeCount = 0;
for (int i = 0; i < count; i++) {
System.out.println(voters[i].name + " 的意见:" + (voters[i].opinion ? "赞同" : "反对"));
if (voters[i].opinion) {
agreeCount++;
}
}
System.out.println("赞同人数:" + agreeCount);
System.out.println("反对人数:" + (count - agreeCount));
}
/**
* 获取投票者姓名
* @return 投票者姓名
*/
public String getName() {
return name;
}
// 静态初始化块,在类加载时执行
static {
System.out.println("Voter类已加载准备开始投票。");
}
}