问答详情
源自:7-1 编程练习

我个人觉得这题对我来讲还是有一定难度,如果不借用排序,我只能做到排出前两名,有能够排出前三名的大佬欢迎留言!


import java.util.Arrays;

public class HelloWorld {

    

    //完成 main 方法

    public static void main(String[] args) {

        

        int[] scores={89 , -23 , 64 , 91 , 119 , 52 , 73};

        

        HelloWorld hello=new HelloWorld();

        System.out.println("成绩前三名为:");

        hello.showThree(scores);

        

    }

    

    //定义方法完成成绩排序并输出前三名的功能

    public void showThree(int[] scores){

        for(int i=0;i<1;i++){

            int max=scores[0],max2=scores[1],max3=scores[2];

            for(int j=0;j<scores.length;j++){

                if(max<scores[j]){

                    max2=max;

                    max=scores[j];

                }

            }

            System.out.println(max);

             System.out.println(max2);

             System.out.println(max3);

        }

    }

    

}


提问者:Coding青天 2019-09-04 23:45

个回答

  • 慕_小黑
    2019-09-05 22:08:19
    已采纳

    public class HelloWorld {

        //完成 main 方法

        public static void main(String[] args) {

            HelloWorld hello=new HelloWorld();

            int[] scores={89,-23,64,91,119,52,73};

            System.out.println("考试前三名为:");

            hello.showTop3(scores);

            

        }    

        //定义方法完成成绩排序并输出前三名的功能

        public void showTop3(int[] scores){

            int temp,count=0;

            for(int i=0;i<scores.length-1;i++){  //类似冒泡排序

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

            if(scores[i]<scores[j]){

            temp=scores[i];

            scores[i]=scores[j];

            scores[j]=temp;

            }

            }

            }

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

            if(scores[i]<0 || scores[i]>100)

            {

            continue;

            }

            count++;

            if(count<=3){

            System.out.println(scores[i]);

            }

           

            }

        }

      

    }


  • 辣条好吃吗
    2019-09-06 08:58:01

    public static  void showThree(int[] arrays){
        int temp = 0;
        for (int i = 0; i < arrays.length - 1; i++) {
            for (int j = 1; j < arrays.length - i; j++) {
                if (arrays[j] < arrays[j - 1]) {
                    temp = arrays[j];
                    arrays[j] = arrays[j - 1];
                    arrays[j - 1] = temp;
                }
            }
        }
        for (int i = arrays.length-1; i >= arrays.length-3 ; i--) {
            System.out.println(arrays[i]);
        }
    }


  • Coding青天
    2019-09-06 08:43:27

    http://www.imooc.com/qadetail/330593,昨晚自己利用冒泡排序重新思考了一下,大家可以看一下。