避免在C#中使用goto语句

时间:2016-12-10 20:42:10

标签: c# goto

我不想使用某种goto语句,但我希望用户在执行默认情况时返回主菜单。怎么样??我知道这是一个简单的问题,但必定会有很多新手遇到非常相似的东西。

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

}

3 个答案:

答案 0 :(得分:10)

将您的注释行替换为:continue;

答案 1 :(得分:1)

正如Nico Schertier所说,你可以通过以下方式实现这一目标:

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

答案 2 :(得分:1)

除了@ Abion47和@Dogu Arslan的答案,您还可以为您的菜单创建一个功能,也可以为您的菜单创建一个功能。

在这个例子中,它将创建一个无限循环菜单

static void Menu()
{
    Console.WriteLine("Menu");
    Console.WriteLine("1) Take me to My fancy menu");
}
static void SwitchFunc(string input)
{
    switch (input)
    {
        case "1":
            Menu();
            string inputB = Console.ReadLine();
            SwitchFunc(inputB);
            break;
    }
}



static void Main(string[] args)
{
    Menu();
    string input = Console.ReadLine();
    SwitchFunc(input);

}