心塞,对象数组排序的问题怎么解决……?
编写了一个投票程序,只差投票后排序输出取得最高票的同学这段程序没写了。代码如下位置已标注出求解答,不明白怎么按照票数排序
程序代码:
public class Student {
private int No;
private String name;
protected int vote;
public Student(int No,String name,int vote){
this.setNo(No);
this.setName(name);
this.setVote(vote);
}
public int getNo() {
return No;
}
public void setNo(int no) {
No = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getVote() {
return vote;
}
public void setVote(int vote) {
this.vote = vote;
}
}
程序代码:import java.util.Arrays;
import java.util.Scanner;
public class VotePart{
private Student stu[]= {new Student(1,"张三",0),new Student(2,"李四",0),new Student(3,"王五",0),new Student(4,"赵六",0)};
public void print(){
for (int i=0;i<this.stu.length;i++){
System.out.println(this.stu[i].getNo()+":"+this.stu[i].getName()+"【"+this.stu[i].getVote()+"】");
}
}
public void Operate(){
this.print();
this.vote();
this.print();
this.getResult();
}
public void vote(){
boolean flag = false;
while(flag==false){
Scanner sc=new Scanner(System.in);
System.out.println("请输入班长候选人代号(数字0结束):");
String id=sc.next();
switch (id){
case "0":{
flag = true;
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("次选票无效,请输入正确的候选人代号!");
}}}
}
public void getResult(){
//这里缺少将对象数组排序的代码
System.out.println("投票最终结果:"+this.stu[0].getName()+"同学,最后以"+this.stu[0].getVote()+"票当选班长!");
}
}
程序代码:
public class Demo {
public static void main(String[] args) {
new VotePart().Operate();
}
}









