Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid goto statement in C#

Tags:

c#

goto

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

}
like image 585
Beginner Avatar asked Sep 05 '26 06:09

Beginner


2 Answers

replace your commented line with: continue;

like image 77
Dogu Arslan Avatar answered Sep 07 '26 19:09

Dogu Arslan


As Nico Schertier said, you can accomplish this with something like the following:

int Size = -1;

while (Size == -1) {
    Console.WriteLine("Pick a coffee Size");
    Console.WriteLine("1: Small");
    Console.WriteLine("2: Medium");
    Console.WriteLine("3: Large");
    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:
            Size = -1;
            Console.WriteLine("This option does not exist");
            break;
    }
}
like image 29
Abion47 Avatar answered Sep 07 '26 19:09

Abion47



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!