package demo;
public
class Student implements Comparable//该
接口用于排序
{
private int sno;
private String name;
private double score;
public Student(int sno, String name, double score)
{
this.sno = sno;
this.name = name;
this.score = score;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public double getScore()
{
return score;
}
public void setScore(double score)
{
this.score = score;
}
public int getSno()
{
return sno;
}
public void setSno(int sno)
{
this.sno = sno;
}
//用于排序
public int compareTo(Object obj)
{
Student stu = (Student)obj;
if(this.score < stu.getScore())
{
return 1;
}
else if(this.score > stu.getScore())
{
return -1;
}
else
{
return 0;
}
}
}
package demo;
import java.util.*;
public class ClassT08
{
private ArrayList list;
public ClassT08()
{
list = new ArrayList();
}
public void addStudent(Student student)
{
list.add(student);
}
public void showAllStudents()
{
Collections.sort(list);//先排序后显示
Iterator it = list.iterator();
while(it.
hasNext())
{
Student student = (Student)it.next();
System.out.println("ID: "+student.getSno());
System.out.println("Name: "+student.getName());
System.out.println("Score: "+student.getScore());
}
}
public Student findStudent(int sno)
{
Iterator it = list.iterator();
while(it.hasNext())
{
Student student = (Student)it.next();
if(student.getSno() == sno)
{
return student;
}
}
return null;
}
}
package demo;
import javax.swing.*;
public class Test
{
public static void main(String[] args)
{
ClassT08 t08 = new ClassT08();
t08.addStudent(new Student(1,"Jacky",90));
t08.addStudent(new Student(2,"Lucy",95));
t08.addStudent(new Student(3,"Tom",80));
t08.showAllStudents();
int id = Integer.parseInt(JOptionPane.showInputDialog("请输入要查询的学员学号: "));
Student stu = t08.findStudent(id);
if(stu == null)
{
JOptionPane.showMessageDialog(null, "未找到!");
}
else
{
JOptionPane.showMessageDialog(null, stu.getSno() + " " + stu.getName() + " " + stu.getScore());
}
}
}