1

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);
2
  • 3
    Remove the continue Commented Oct 4, 2013 at 21:59
  • I dont understand how a developer can use a do-while or continue is something awful. Commented Oct 4, 2013 at 22:04

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0

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)

1 Comment

".. and i want it to run infinitly"
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.