本帖最后由 古银平 于 2012-6-2 00:26 编辑
也可以使用冒泡排序,对数组排序的都可以,可以看看API文挡的排序方法,直接调用也行- class StudentDemo
-
- {
-
- public static void main(String[] args)
- {
- Student arr[] = //定义学生的引用类型
- {
- new Student("zhangyang",24,80),
- new Student("liyang",24,90),
- new Student("wangyang",24,78),
- new Student("langyang",24,66),
- new Student("hangyang",24,89)
- };
-
- /*
- 把这个初始化到一个Student 类型的数组里
- Student stu = new Student("zhangyang",24,80);
-
- Student stu1 = new Student("liyang",24,90);
-
- Student stu2 = new Student("wangyang",24,78);
-
- Student stu3 = new Student("langyang",24,66);
-
- Student stu4 = new Student("hangyang",24,89);
-
- Student[] arr = {stu,stu1,stu2,stu3,stu4};
- */
- Student temp; //学生类型的变量,用于交换数组元素。
-
- for (int i = 0; i<arr.length; i++) //对成绩进行排序
- {
- for (int j=i+1; j<arr.length; j++)
- {
- if (arr[i].getExam()<arr[j].getExam()) //排序语句,我这里用选择排序
- {
- temp = arr[i];
- arr[i] = arr[j];
- arr[j] = temp;
- }
- }
-
- }
-
- System.out.println("学生按成绩排序");
-
- for (int i=0;i<arr.length ;i++ )
-
- {
-
- System.out.println("第"+(i+1)+"名:"+arr[i].getName()+" 成绩:"+arr[i].getExam());
-
- }
-
-
- }
-
-
-
- }
-
- class Student
-
- {
-
- Student(){}
-
- Student(String name,int age,int exam)
-
- {
-
- this.name=name;
-
- this.age=age;
-
- this.exam=exam;
-
- }
-
- private String name;
-
- private int age;
-
- private int exam;
-
- public void setName(String name)
-
- {
-
- this.name = name;
-
- }
-
- public String getName()
-
- {
-
- return name;
-
- }
-
- public void setAge(int age)
-
- {
-
- this.age = age;
-
- }
-
- public int getAge()
-
- {
-
- return age;
-
- }
-
- public void setExam(int exam)
-
- {
-
- this.exam = exam;
-
- }
-
- public int getExam()
-
- {
-
- return exam;
-
- }
-
- }
复制代码 |