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

Time:09-02

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?

CodePudding user response:

You are not updating the ageAnswer inside the loop, so if it is incorrect, it will just enter an infinite loop. You are also not handling the case where the user enters something other than a number.

To handle both of these cases you could so something like:

int ReadInt(string message, string failMessage){
   Console.WriteLine(message);
   while(!int.TryParse(Console.ReadLine(), out var result){
       Console.WriteLine(failMessage);
    }
   return result
}
...
while(true){
   var age = ReadInt("enter age", "not a number, enter age");
   if (ageAnswer != age)
      Console.WriteLine("This is not your real age");
   else{
      Console.WriteLine($"Correct, you are {age} years old");
      return;
   }
}

I would recommend avoiding using Environment.Exit, since this would make your program difficult to reason about, when any method could potentially result in just exiting the process. Try to make methods take some parameter and either do something or return a value. Ideally methods should be pure i.e. just take some parameters, do some computation only using the parameter values, and return a result, without causing any side effects. These methods are very easy to reason about.

CodePudding user response:

You can move the readLine into the while loop like I did below. The condition of the while is being evaluated every time the program loops, so it will ask for a number every time.

using System;

class Program {
    static void Main() {
        int age = 4;
        while (Convert.ToInt32(Console.ReadLine()) != age) {
          Console.WriteLine("this is not your real age");
        }
      Console.WriteLine($"Correct, you are {age} years old");
    }
}

Edit: Also as JHBonarius said in the comments, this does not test that the answer is indeed a int and it will crash if you get a bad input. Since you said you are a begginer I didn't want to add more to not confuse you but you could, and should, ensure that this does not happen, either by testing the nature of your input beforehand of using a try-catch statement, or using Int32.TryParse. There is another answer here that describes a safer way of doing this.

CodePudding user response:

You need to move the Console.ReadLine inside the loop and add a break condition. Further it's better to enclose the Convert.ToInt32 inside a try...catch block to manage wrong inputs

static class Program
{
   static int Main()
    {
        int age = 35;
        Console.WriteLine("Enter your age:");
        while (true)
        {
            int ageAnswer;
            try
            {
                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");
                    break;
                }
            }
            catch (Exception)
            {
                Console.WriteLine($"Please enter a number");
            }
        }
        // some other code

        return 0;
    }
}

CodePudding user response:

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

  •  Tags:  
  • c#
  • Related