1个回答
展开全部
public class Student implements Comparable<Student>{
private String sno;
private String sname;
private String sclass;
private int sage;
public String getSno() {
return sno;
}
public void setSno(String sno) {
this.sno = sno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSclass() {
return sclass;
}
public void setSclass(String sclass) {
this.sclass = sclass;
}
public int getSage() {
return sage;
}
public void setSage(int sage) {
this.sage = sage;
}
public String outPut(){
return " 学号: " + this.getSno() + " 姓名: " + this.getSname() + " 班级: " + this.getSclass() +
" 年龄: " + this.getSage();
}
@Override
public int compareTo(Student o) {
if(this.sage > o.sage){
return 1;
}else if(this.sage < o.sage){
return -1;
}else {
return 0;
}
}
}
上面第一个java代码 Student.java
下面是StudentDisplayDemo.java代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class StudentDisplayDemo {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
Scanner sc = new Scanner(System.in);
for(int i = 0; i < 5; i++){
Student stu = new Student();
System.out.print("输入第"+ (i + 1) +"位学生的学号: ");
stu.setSno(sc.next());
System.out.print("输入第"+ (i + 1) +"位学生的姓名: ");
stu.setSname(sc.next());
System.out.print("输入第"+ (i + 1) +"位学生的班级: ");
stu.setSclass(sc.next());
System.out.print("输入第"+ (i + 1) +"位学生的年龄: ");
stu.setSage(sc.nextInt());
list.add(stu);
}
for(int i = 0; i < 5; i++){
System.out.println("显示第"+ (i + 1) +"位学生的信息: ");
System.out.println(list.get(i).outPut());
}
//排序
Collections.sort(list);
System.out.println("排序后输出学生信息: ");
for(int i = 0; i < 5; i++){
System.out.println(list.get(i).outPut());
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询