将‘循环输入’,放到循环之初 与 循环之尾 的区别

来源:互联网 发布:怎样躲过淘宝售假排查 编辑:程序博客网 时间:2024/05/11 19:48

循环体:输入-判断-重复或结束

1.导致多输入一次才结束: 放到循环之初 :

 public static void find_top_5_8() {        Scanner input=new Scanner(System.in);        int num=0,score=0,max=0,count=0;        String name="",name_max="";        System.out.println("Enter how many students: ");        num=input.nextInt();        //先在外部输入第一次的输入值:        System.out.println("Enter the name and it's score: ");        name=input.next();        score=input.nextInt();        while (count < num) {            if (max < score) {                max=score;                name_max=name;            }                count++;            //在循环的尾部,输入下一个输入值                name=input.next();                score=input.nextInt();            //显化:每次的输入后,循环体内的变化            System.out.println("The top name,score,and count is: "+name_max+" "+max+" "+count);            }        System.out.println("The top score student is: "+name_max);    }产生的结果:
Enter how many students: 3Enter the name and it's score: a 11b 22The top name,score,and count is: a 11 1c 33  此时,又进入循环体,count++后又要求一次输入,才结束循环,外输入后,循环体: 判断-输入-重复或结束The top name,score,and count is: b 22 2d 44   要多输入一对值,才能运行完The top name,score,and count is: c 33 3The top score student is: c

2.正确方法: 放在在循环之初,且不在外部先输入值:       

public static void find_top_5_8() {        Scanner input=new Scanner(System.in);        int num=0,score=0,max=0,count=0;        String name="",name_max="";        System.out.println("Enter how many students: ");        num=input.nextInt();        while (count < num) {          在每次循环初始,输入值,才能满足 循环体:输入-判断-重复或结束            System.out.println("Enter the name and it's score: ");            name=input.next();            score=input.nextInt();            if (max < score) {                max=score;                name_max=name;            }                count++;            //显化:每次的输入后,循环体内的变化            System.out.println("The top name,score,and count is: "+name_max+" "+max+" "+count);            }        System.out.println("The top score student is: "+name_max);    }

运行结果:

Enter how many students: 3Enter the name and it's score: a 11The top name,score,and count is: a 11 1Enter the name and it's score: b 22The top name,score,and count is: b 22 2Enter the name and it's score: c 33The top name,score,and count is: c 33 3The top score student is: c


原创粉丝点击