您的位置:首页 > 职场人生

黑马程序员:学生类按成绩排序问题

2012-06-03 07:30 323 查看
--------------------android培训java培训、期待与您交流! ------------------
 

现在才发现我用集合类实现的做法过于繁杂。看到黑马论坛里的同学贴出的代码,感觉有点自惭形秽,其实这个问题非常简单,只是自己把问题想得复杂了,看到这么简洁高效的实现,再对比我写的代码。呵呵,既是惊讶又是惊喜!直接在构造函数里初始化对象,比起我在集合里建立对象,省事多了。同时代码清晰,有层次感,还便于后期的维护。把代码贴出来学习下:

class Sort

{

        public static void main(String[] args)

        {

                Student stu0 = new Student("stuA",24,80);

                Student stu1 = new Student("stuB",24,90);

                Student stu2 = new Student("stuC",24,78);

                Student stu3 = new Student("stuD",24,66);

                Student stu4 = new Student("stuE",24,89);

                Student[] arr = {stu0,stu1,stu2,stu3,stu4};

                for (int i = 0;i<arr.length;i++ )

                {

                        for(int j = i+1;j<arr.length;j++)

                        {

                                if (arr[j].getExam()<arr[i].getExam())

                                {

                                 Student temp = arr[j];

                                         arr[j] = arr[i];

                                         arr[i] = 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;

        }

}

 

---------------------- android培训java培训、期待与您交流! ----------------------

详细请查看:http://edu.csdn.net/heima
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string android class java
相关文章推荐