(1)功能描述
有一个班采用民主投票方法推选班长,班长候选人共4位,每个姓名及代号分别位“张三 1;李四 2;王五3;赵六 4”。程序操作员将每张选票上所填的代号(1,2,3,4)循环输入电脑,输入数字0结束输入,然后将所有候选人的得票情况显示出来,并显示最终结果。
(2)具体要求
- 要求用面向对象方法,编写学生类Student,将候选人姓名、代号和票数保存道类Student中,并实现相应的setter getter方法。
- 输入数据前,显示各位候选人的代号及姓名。
- 循环执行接收键盘输入的班长候选人代号,直到输入的数字为0,结束选票的输入工作。
- 在每次输入的而选票后要求验证该选票是否有效,即如果输入的数字不是0、1、2、3、4这5个数字之一,或输入的一串字母,应显示错误提示信息“此票无效,请输入正确的候选人代号!”,并继续等待输入。
- 输入结束后显示所有候选人的得票情况。
- 输出最终当选者的相关信息。
1、建立学生类,这个类里面需要保存又编号、姓名、票数。
package demo.vo;
public class Student implements Comparable<Student>{
private long sid ;
private String name ;
private int vote;
public Student(long sid, String name, int vote) {
super();
this.sid = sid;
this.name = name;
this.vote = vote;
}
@Override
public String toString() {
return "【" + this.sid + "】姓名:" + this.name + "、票数:" + this.vote;
}
@Override
public int compareTo(Student stu) {
return stu.vote - this.vote;
}
}
2、定义投票处理的业务接口
package demo.service;
import demo.vo.Student;
public interface IVoteService {
public boolean inc(long sid);//根据编号进行增长
public Student[] result();//获取投票的结果
public Student[] getData();//获取全部数据
}
3、定义VoteServiceImpl的子类
package demo.service.impl;
import java.util.Arrays;
import demo.service.IVoteService;
import demo.vo.Student;
public class VoteServiceImpl implements IVoteService {
private Student [] students = new Student[] {
new Student(1,"张三",0),new Student(2,"李四",0),
new Student(3,"王五",0),new Student(4,"赵六",0)};
@Override
public void inc(long sid) {
for (int x = 0 ; x <students.length; x++) {
if(this.students[x].getSid() == sid) {//获取指定编号
this.students[x].setVote(this.students[x].getVote()+1);//票数增长
}
}
}
@Override
public Student[] getData() {
return this.students;
}
@Override
public Student[] result() {
Arrays.sort(this.students);
return this.students;
}
}
4、定义菜单信息显示类
package demo;
import demo.factory.Factory;
import demo.service.IVoteService;
import demo.vo.Student;
public class Menu {
private IVoteService voteService;
public Menu() {
this.voteService = Factory.getInstance();
this.vote();
}
public void vote() {// 投票处理
Student stu[] = this.voteService.getData();
for (Student temp : stu) {
System.out.println(temp.getSid() + ":" + temp.getName() + "【" + temp.getVote() + "】");
}
int num = 10;
while (num != 0) {// 循环投票
num = InputUtil.getInt("请输入班长候选人代号(数字0结束).");
if (num != 0) {
if (!this.voteService.inc(num)) {
System.out.println("此选票无效,请输入正确的候选人代号!");
}
}
}
System.out.println("投票最终果 :");
stu = this.voteService.result();
System.out.println(stu[0].getName() + "同学,以" + stu[0].getVote() + "票当选班长!");
}
}
5、定义工厂类
package demo.factory;
import demo.service.IVoteService;
import demo.service.impl.VoteServiceImpl;
public class Factory {
private Factory() {}
public static IVoteService getInstance() {
return new VoteServiceImpl();
}
}
6、定义测试类
package demo;
import demo.factory.Factory;
public class IOCaseDemo {
public static void main(String[] args) {
new Menu();
}
}
参考资料:https://edu.aliyun.com/lesson_1012_9025#_9025