简体   繁体   中英

Why can't I enter the while loop?

class Labo21
{
    public static void main(String [] arguments){
        int n;
        int i;
        double somme;

        System.out.print("Positive number: ");
        n = Clavier.lireInt(); //keyboard

        if( n <= 0){
            System.out.print("ERROR");
        }else{
            i = 2;
            somme = 1;

            while (n <= i){
                somme = somme + 1.0 / i;
                i = i + 1;
            }
            System.out.print("Result: " + somme);
        }
    }
}

I try to know why I cannot enter the while loop.

Provide 1 or 2 as Clavier.lireInt() and you will go inside the loop.

Example :

class Labo21 {
    public static void main(String[] arguments) {
        int n;
        int i;
        double somme;
        System.out.print("Positive number: ");
        n = 1; //Clavier.lireInt(); //keyboard
        if (n <= 0) {
            System.out.print("ERROR");
        } else {
            i = 2;
            somme = 1;
            while (n <= i) {
                System.out.println("in loop");
                somme = somme + 1.0 / i;
                i = i + 1;
            }
            System.out.print("Result: " + somme);
        }
    }
}

Your number needs to be greater than 0 based on your if condition. To get into the while loop, your number needs to be less than or equal to 2 since you set i equal to 2. So your options are 1 or 2 .

With that being said, once you're inside the while loop, you will never be able to exit (you have created an infinite loop) because n will always be less than i . Your i is incrementing by 1 on each loop iteration, and n is never changing, so it will never be greater than i . You should add a terminating condition (some way to exit the loop).

This code has a problem with its mentality. You are lucky that it is not going into the loop though. If it so, it would run without stopping and you cannot understand it.

BECAUSE: in your code you say the condition of while loop is i should be equal to or greater than n. I guess Clavier.lireInt(); getting value from user. So if user enters 1 condition will be while( 1 <= 2) then it will go through the while loop. Increment the i, then i will be 3 again greater than n, increment i then 4 will be greater than n. It will go like that.

I thing your condition should be :

while(n>=i)

Then you can enter n as 5 and count i = 2 to 5.

Am I correct ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM