Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Console.ReadLine: How to wait for correct input before exiting?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading