题目:
编写一个应用程序,用户分别从两个文本框输入学生的姓名和分数,程序按成绩排序将这些学生的姓名和分数显示在一个文本区中。
代码示例
student类
package oop.lesson.text3.text2;
/**
* 学生类
* @author zc
*/
public class Student implements Comparable<Student>{
private String name;//姓名
private int score;//成绩
public Student(String name, int score) {
this.name = name;
this.score = score;
}
/** 公共的get(),set()方法 */
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
/** 重写Comparable接口中的方法,可以控制集合的升序或降序 */
@Override
public int compareTo(Student o) {
return o.getScore()-this.getScore();
}
}
测试类
package oop.lesson.text3.text2;
import java.util.*;
/**
* 学生测试类
*/
public class Text {
public static void main(String[] args) {
/** 创建student对象,并调用其有参构造,然后创建list集合,并将student对象存入list集合中 */
Student s1 = new Student("张三",95);
Student s2 = new Student("李四",85);
Student s3 = new Student("赵武",93);
Student s4 = new Student("王柳",70);
Student s5 = new Student("琪琪",80);
List<Student> list = new ArrayList<Student>();
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
/** 接受控制台输入的数据,并存在student对象中,然后添加到list集合中 */
Scanner sc = new Scanner(System.in);
System.out.println("请输入姓名");
String name = sc.next();
System.out.println("请输入成绩");
int score = sc.nextInt();
Student newstu = new Student(name,score);
list.add(newstu);
/** 使用Collections接口的sort方法,对list集合进行排序 */
Collections.sort(list);
/** 使用循环输出list集合 */
for (Student s : list){
String sname = s.getName();
int sscore = s.getScore();
System.out.println(sname+" "+sscore);
}
}
}
输出结果