novice here:
I am writing a simple console app that asks for your age. If you enter a correct age, then you the program doesn’t ask you anymore. If you put the wrong age, then it keeps asking you until you get it right.
Here is the sample code:
int age = 35;
int ageAnswer = Convert.ToInt32(Console.ReadLine());
while(true)
{
if (ageAnswer != age)
{
Console.WriteLine("This is not your real age");
}
else
{
Console.WriteLine($"Correct, you are {age} years old");
System.Environment.Exit(0);
}
}
This works, but not completely. If you give a wrong age, the text is printed indefinitely. And it makes sense because it’s executing what’s inside the block, but how do I jump back to asking the question again until the user is right?
>Solution :
As Daniel mentioned in comments you just need to move your ReadLine into while-loop.
So resulting code should look like this:
int age = 35;
int ageAnswer;
while(true)
{
ageAnswer = Convert.ToInt32(Console.ReadLine());
if (ageAnswer != age)
{
Console.WriteLine("This is not your real age");
}
else
{
Console.WriteLine($"Correct, you are {age} years old");
System.Environment.Exit(0);
}
}