0

I am having trouble figuring out how to break out of a loop that contains a switch statement. i need to press 0 twice to exit the console why? how can i fix it to exit from the first time

public void Start()
{
    int choice = 0;
    bool trueNumber = false;

    do
    {
        ShowMenu(); // display the menu
        Console.Write("Your Choice : ");
        trueNumber = int.TryParse(Console.ReadLine(), out choice);        

        if (!trueNumber)
            Console.WriteLine("Your Choice must be an integer. Try again.");

        switch (choice) // select the relevant function based on user input
        {
            case 1:
                CalculateCelsiusToFahrenheit();
                break;
            case 2:
                CalculateFahrenheitToCelsius();
                break;
            case 0:
                return;     // exit when i press 0          
            default:
                Console.WriteLine("Invalid Option: Choose 0, 1, or 2 Thank you ");
                break;
        }
    } while (choice != 0);
}
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Nash Nash
  • 1
  • 3
  • 1
    FYI: `TryParse` will set `choice` to 0 if the supplied text is not a valid number. – Sean Feb 04 '21 at 09:59
  • 1
    What's the code that calls `Start()` ? – Fildor Feb 04 '21 at 10:01
  • 2
    This looks fine regarding the exiting. If the user inputs ZERO, it will exit. You can replace the `return` with a simple `break` as it will break out of the do-while loop since `choice == 0`. – GregorMohorko Feb 04 '21 at 10:02
  • 2
    _"i need to press 0 twice to exit the console why?"_ - do you happen to start the program from the IDE (Visual Studio). Depending on settings, VS adds a "keep open until key pressed" for you. Could that be what you are seeing here? Try to build in Release mode and execute the .exe from cmd-line. – Fildor Feb 04 '21 at 10:05
  • 1
    I just ran your code and it works perfectly fine.. – Peter Henry Feb 04 '21 at 10:06
  • @PeterHenry yes but when i press 0 as the first option it did not exit until i press 0 again – Nash Nash Feb 04 '21 at 10:42
  • The only difference is that I commented out ShowMenu().. Is this prompting the user to enter a number? Because it will then do it again 2 lines later.. – Peter Henry Feb 04 '21 at 11:27

1 Answers1

0

If you are running this from an IDE (like Visual Studio), the default behavior for console applications is to end with a "Press any key to continue." so it waits with the output displayed.

related answer: VS setting

Jenda
  • 11
  • 2