java输入10个身高,输出最高,要求用对象数组类,求教我写的这个错在哪里。

package scheight;
public class Student { int height;
}

package scheight;
import java.util.*;
public class Height {

public Student getHigher(Student[] stu){
Arrays.sort(stu);
return stu[stu.length-1];
}
public static void main(String[] args){
Height h=new Height();
Student[] stu=new Student[10];
Scanner input=new Scanner(System.in);
for(int i=0;i<stu.length;i++){
System.out.print("请输入第"+(i+1)+"个学生的身高:");
stu[i]=new Student();
stu[i].height=input.nextInt();

}
Student s=h.getHigher(stu);
System.out.print(s);
}
}

public Student getHigher(Student[] stu){
Arrays.sort(stu);
return stu[stu.length-1];
}
LZ
Arrays.sort()的确可以用来给数组排序 但是你查了API会发现有多种参数 因为每种参数比较的东西不一样 在比较时代码实现也不一样 你传入的Student对象是自定义的对象 对于在容器中给自定义的对象做比较 你想你如果做为java虚拟机 你本身不认识Studnet是个什么东西 别人让你排序 你知道按什么条件排嘛
需要实现Comparator接口的compare()方法 在compare方法中来具体实现自己需要的特定比较方式追问

compare方法还没学,想问下如果不比较数组,通过sort方法进行排序每个对象的身高数值,可以实现吗?

追答

貌似不行的 你要用容器的排序方法 而且传的是自定义的对象是不能直接比较的
而且LZ你要知道 System.out.print(s);这句话就算打印出来了 你也得不到你想要的结果 这个将会打印s这个Studnet对象在内存中的地址

追问

谢谢,已经通过循环比较的方法实现!

追答

其实LZ你不就是为实现得到最高身高的同学吗 比较的实际上是身高 其实应该把这个比较封装在Studnet中 不过你是这样写的 我就随便改了下 这样功能是能实现了 但是并不是规范的
class Student {
int height;

}

public class Height {

public static void main(String[] args){

int temp = 0;//用于记录身高
int id=0;//用于记录姓名
Student[] stu=new Student[5];
Scanner input=new Scanner(System.in);
for(int i=0;itemp){
temp = stu[i].height;
id = i+1;
}
}
System.out.print("第"+id+"个同学身高最高"+"---------->"+temp);
}
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-09-22
楼主你好!
我发现楼主在对自己的对象进行排序时调用了
Arrays.sort();
但是不知道楼主有没有了解过该方法是需要对你的对象实现Comparable接口的
如果没有实现该接口 ,是无法完成排序的。
楼主要做的是在你的Student类继承该接口并实现该接口中对Height属性值的比较即可,
至于是递增排序还是递减排序就得看楼主是如何实现Comparable接口的方法了。
第2个回答  2012-09-22
错在这里
public Student getHigher(Student[] stu){
Arrays.sort(stu);
return stu[stu.length-1];
}追问

请问应该怎么修改。如果必须用sort方法做的话,我是初学者,很多不懂,谢谢了!

第3个回答  2012-09-22
Arrays.sort(stu);stu的对象必须实现Comparator接口
相似回答