因为程序中要使用对象数组的排序方式,所以在Student类里要实现Comparable接口
学生类代码如下:
此类的对象数组可以使用Arrays.sort()直接排序。
定义一个操作数据的类:
定义一个操作器:
package 实例二; import java.io.IOException; import java.util.Arrays; public class Operate { boolean flag = true; public Operate() throws IOException{ while(flag){ this.vote(); } this.printInfo(); //输出投票之后的票数 this.getResult(); } private void getResult(){ Arrays.sort(this.stu); //排序 System.out.println("投票最终结果:" + this.stu[0].getName() + "同学最终以" + this.stu[0].getVote()+ "票当选班长"); } private Student stu[] = {new Student(1,"张三",0), new Student(2,"李四",0), new Student(3,"王五",0), new Student(4,"赵六",0)}; public void printInfo(){ for(int i=0;i<stu.length;i++){ System.out.println(this.stu[i].getStuNo() + ":" + this.stu[i].getName() + " 【 " + this.stu[i].getVote() + "】"); } } public void vote() throws IOException{ InputData input = new InputData(); int num = input.getInt("请输入班长候选人的代码(数字0结束)", "此票无效,请输入正确的候选人号码"); switch(num){ case 0:{ this.flag = false; break; } case 1:{ this.stu[0].setVote(this.stu[0].getVote() + 1); break; } case 2:{ this.stu[1].setVote(this.stu[1].getVote() + 1); break; } case 3:{ this.stu[2].setVote(this.stu[2].getVote() + 1); break; } case 4:{ this.stu[3].setVote(this.stu[3].getVote() + 1); break; } default:{ System.out.println("此选票无效,请正确输入候选人号码"); } } } }
