Search code examples
c#console-applicationrider

Console application requiring input multiple times


I'm attempting to get a more immediate response to the start of my program, this is rough and not a finished product by any means.

When I attempt to enter "Y" or "N" as per the prompt, I have to enter it several times for the console to recognize the input and spit out the appropriate response.

I'd prefer if it only took one input entry to output the respective response. As of right now, this is not the case. I have also attached console output to put into perspective. As you can see, the console wants me to input Y twice, rather than once which is what I intend for it to do (same goes for N).

Code:

internal static class Program
{
   public static void Main()
   {
        Console.WriteLine("Hello, Simon!");
        Console.WriteLine("Shall we begin?, Please Enter: Y/N");
    
        Console.ReadLine();
    
        if (Console.ReadLine() == "Y")
        {
            Console.WriteLine("Alright, Here we go!");
        }
        else if (Console.ReadLine() == "N")
        {
            Console.WriteLine("Adios Simon!");
        }
    }
}

Console:

Hello, Simon! Shall we begin?, Please Enter: Y/N

Y

Y

Alright, Here we go!

I've attempted to rectify my issue with the forementioned code with either using line breaks or additional Console.ReadLine(); code, but nothing has made the mentioned issue disappear, as of right now my input still is required more than once to get a output.

For example:

Y

Y

is required for an response in the console, id like to make it look more like this:

Hello, Simon!

Shall we begin?, Please Enter: Y/N

"Y"

Alright, Here we go!


Solution

  • Every time you use Console.ReadLine(), you're requesting to read from the console once.

    The solution is to have a single Console.ReadLine() and assign it to a variable:

    string input = Console.ReadLine();
    
    if (input == "Y")
    {
        //...
    }
    else if (input == "N")
    {
        //...
    }