Search code examples
c#while-loopreadline

How to get the program in C# to react to user input


So below is the code I have. When i hit 5 I have to hit enter 5 times to get the program to write the line and pressing 6 doesn't work at all. Any solution would be appreciated.

            Boolean keepRunning = true;
            while (keepRunning = true)
            {
                if (Console.ReadLine() == "1")
                {
                    Console.WriteLine("Still running");
                }
                else if (Console.ReadLine() == "2")
                {
                    Console.WriteLine("Still running2");
                }
                else if (Console.ReadLine() == "3")
                {
                    Console.WriteLine("Still running3");
                }
                else if (Console.ReadLine() == "4")
                {
                    Console.WriteLine("Still running4");
                }
                else if (Console.ReadLine() == "5")
                {
                    Console.WriteLine("Still running5");
                }
                else if (Console.ReadLine() == "6")
                {
                    keepRunning = false;
                }
            }

Solution

  • You're waiting for an enter with each Console.ReadLine();. Read the input only once and then decide what to do.

    And you should change your while condition to keepRunning == true. With your current version you set keepRunning to true in your condition and that's why it seems like "6" is not working ;)

    Boolean keepRunning = true;
    while (keepRunning == true)
    {
        string input = Console.ReadLine();
    
        if (input == "1")
        {
            Console.WriteLine("Still running");
        }
        else if (input == "2")
        {
            Console.WriteLine("Still running2");
        }
        else if (input == "3")
        {
            Console.WriteLine("Still running3");
        }
        else if (input == "4")
        {
            Console.WriteLine("Still running4");
        }
        else if (input == "5")
        {
            Console.WriteLine("Still running5");
        }
        else if (input == "6")
        {
            keepRunning = false;
        }
    }
    

    You can use a switch statement to make it even better.

    switch(input)
    {
        case "1":
            Console.WriteLine("Still running");
            break;
        case "2":
            Console.WriteLine("Still running");
            break;
        case "3":
            Console.WriteLine("Still running");
            break;
        case "4":
            Console.WriteLine("Still running");
            break;
        case "5":
            Console.WriteLine("Still running");
            break;
        case "6":
            keepRunning = false;
            break;
        default:
            break;
    }