(完整版)Java程序设计实验报告 下载本文

this.weight = weight; }

public void speak() {

System.out.println(\我是\ + name + \,我的身高是\ + height + \,我的体重是\ + weight); }

@Override

public int compareTo(Student o) { int flag;

if(this.weight

else{

flag =1; }

return flag; }

@Override

public String toString() {

return \[name=\ + name + \height=\ + height + \weight=\ + weight + \; } }

public class Test {

public static void main(String[] args) { int i;

Student ps[] = new Student[6];

ps[0] = new Student(\张三\, 170, 110); ps[1] = new Student(\李四\, 168, 120); ps[2] = new Student(\王五\, 165, 115); ps[3] = new Student(\赵六\, 172, 121); ps[4] = new Student(\周七\, 160, 100); ps[5] = new Student(\郑八\, 166, 119);

System.out.println(\排序前数组元素的序列是:\); for (i = 0; i < ps.length; i++) { ps[i].speak(); }

Arrays.sort(ps);//调用Java系统类中的排序方法对ps数组排序

}

}

System.out.println(\排序后数组元素的序列是:\); for (i = 0; i < ps.length; i++) { System.out.println(ps[i]); }

实验结果:

实验心得体会:

本次实验主要掌握对compareTo方法的重写,当返回值为0的时

候此方法调用会出现错误,导致不进行排序,需要特别注意。这个实验主要使我们掌握了对类的接口的实现,和数组的比较,并使我们理解其中的细节。