简体   繁体   中英

infinite do while loop?

I want to make a loop that will print wrong answer each time answer is not 1 2 3 or 4 .... and I want it to run infinitly, mine don't detect if the answer is right or wrong it just print out invalid answer, then asks again, then crash! I don't know why it does that.

Here's my code don't read the "text" part because it's in French just look a the code!

System.out.println("Veuillez Choisir 1 des 4 groupes alimentaires suivants: (1)Légumes et fruits , (2) Produit cérealiers , (3) Laits et Substitues , (4) Viandes et substitues :");
        System.out.println("\n");
    answer =  Clavier.lireIntLn();
    do {
        System.out.println("Votre choix est invalide");
         System.out.println("Veuillez Choisir 1 des 4 groupes alimentaires suivants: (1)Légumes et fruits , (2) Produit cérealiers , (3) Laits et Substitues , (4) Viandes et substitues :");
            answer =  Clavier.lireIntLn();
                continue;
        }while (answer<1 && answer>5);

First you need to remove the continue .

After you do that, you will need to deal with this:

while (answer<1 && answer>5)

This will never happen. You need to do this:

while (answer<1 || answer>5)

You can't have a number be less than 1 AND greater than 5.

The continue statement causes the program execution to jump back to do immediately without even evaluate the while-condition. That means the condition is never evaluated and the loop becomes infinite.

Remove the continue, and the loop will be left when the while-condition is false. Unfortunately it will always be false, because a value can't be below 1 and above 5. When you want to continue until the user inputs 5, then try

while (answer != 5)

When you want (as written) allow any answer except 1, 2, 3 or 4, do this

while(answer >= 1 && answer <= 4);

The code would be more like this:

do
{
    System.out.println("Veuillez Choisir 1 des 4 groupes alimentaires suivants: (1)Légumes et fruits , (2) Produit cérealiers , (3) Laits et Substitues , (4) Viandes et substitues :");
    System.out.println("\n");
    answer =  Clavier.lireIntLn();
    if( answer < 1 || answer > 4  )
    {
        //print your error message here
    }
}while(true)

The continue prevents it from reaching the while statement. Remove it and it will hit the while condition.

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