Reputation: 13
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);
Upvotes: 1
Views: 103
Reputation: 23483
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.
Upvotes: 3
Reputation: 7782
The continue prevents it from reaching the while statement. Remove it and it will hit the while condition.
Upvotes: 0
Reputation: 630
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)
Upvotes: 0
Reputation: 69663
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);
Upvotes: 1