(一) public class Student implements Comparable<Student>
{
private int score1,score2,score3;
private float pscore;
private int id;
private String name;
public Student(int id,String name,int score1,int score2,int score3)
{
this.id=id;
this.name=name;
this.score1=score1;
this.score2=score2;
this.score3=score3;
this.pscore=(this.score1+this.score2+this.score3)/3;
}
public String getName()
{
return this.name;
}
public int compareTo(Student stu)
{
if(this.pscore>stu.pscore)
return 1;
else return -1;
}
public String toString()
{
String s="学号:"+this.id+";姓名:"+this.name+";平均成绩为:"+this.pscore+"\n";
return s;
}
}
(二)
public class Add
{
private ArrayList<Student> array;
//构造方法实例化array
public Add()
{
array=new ArrayList<Student>();
}
//向array中添加Student的对象
public void add(Student stu)
{
array.add(stu);
}
//从array中移除指定姓名的Student对象
public void remove(String name)
{
Iterator<Student> iter = array.iterator();
while(iter.hasNext())
{
if(iter.next().getName().equals(name))
{
iter.remove();
System.out.println("正在删除...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("删除成功!");
break;
}
else
{
System.out.println("正在匹配下一个人...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//把array中的数据转成Student的数组,用Arrays.sort()排序后输出(排序的前提是Student类中实现了Comparable<T>接口)
public void showAll()
{
Student[] st=array.toArray(new Student[]{});
Arrays.sort(st);
for(Student stu:st)
{
System.out.println(stu);
}
}
}
(三)
package org.hwh.jiHe2;
public class Test
{
private Student st1,st2,st3,st4;
public static void main(String[] args)
{
Add ad=new Add();
int[] id={1,2,3,4,5};
String[] name={"张山","李四","王五","赵六","狗屎"};
int[] score1={50,89,56,88,56};
int[] score2={89,79,90,98,67};
int[] score3={70,66,76,45,66};
Student[] stu=new Student[5];
for(int i=0;i<5;i++)
{
stu[i]=new Student(id[i],name[i],score1[i],score2[i],score3[i]);
ad.add(stu[i]);
}
ad.remove("狗屎");
try {
Thread.sleep(1000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("正在排序输出....");
try {
Thread.sleep(1000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
ad.showAll();
}
}