Search code examples
c#goto

Avoid goto statement in C#


I don't want to use some sort of goto statement, but I want the user to return to the main menu when the default case is executed. How?? I know this is a simple problem, but there must be lots of newbie who come across something very similar.

static void buycoffee()
{
    Double price = 0;
    int x = 0;
    while (x == 0)
    {
        Console.WriteLine("Pick a coffee Size");
        Console.WriteLine("1: Small");
        Console.WriteLine("2: Medium");
        Console.WriteLine("3: Large");
        int Size = int.Parse(Console.ReadLine());
        switch (Size)
        {
            case 1:
                price += 1.20;
                break;
            case 2:
                price += 1.70;
                break;
            case 3:
                price += 2.10;
                break;
            default:
                Console.WriteLine("This option does not exist");
                ///how to return to the main menu here
                break;
        }
        Console.WriteLine("Would you like to buy more coffee?");
        String Response = Console.ReadLine().ToUpper();
        if (Response.StartsWith("Y"))
        {
            Console.Clear();
        }
        else
        {
            x += 1;
        }
    } 
Console.WriteLine("The total bill comes to £{0}", price.ToString("0.00"));
}

}

Solution

  • replace your commented line with: continue;