【问题标题】:How to not exit out of method after switch C#切换C#后如何不退出方法
【发布时间】:2021-04-06 20:14:44
【问题描述】:

所以我想知道如何使一个包含 switch 语句的方法在案例完成后不关闭。这是我所做的。

public static int Store(int cashyo)
    {
        int open = 1;

        while (open != 0)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("What would you like to buy?");
            Console.ForegroundColor = ConsoleColor.Red;
            string option = Console.ReadLine();

            switch (option)
            {
                case "bye":
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Leaving store.");
                    Thread.Sleep(1500);
                    open = 0;
                    break;

                case "list":
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Bike");
                    break;

                case "bike":
                    Console.ForegroundColor = ConsoleColor.Green;
                    if (cashyo >= 300)
                    {
                        Console.WriteLine("Purchased Bike for 300 USD!");
                        return (cashyo-3000);
                    }
                    else
                    {
                        Console.WriteLine("Canot purchase Bike. Insufficient amount of funds.");
                        return cashyo;
                    }
                    break;

            }
            return cashyo;
        }
        return cashyo;
    }

cashyo 是 main 中实际使用的货币的虚拟变量。我想这样做,如果我输入“bike”,它会购买自行车,然后再问我想做什么,因为 open 仍然不是 0。

【问题讨论】:

  • 你知道return关键字的作用吗?
  • @BenVoigt 我猜不是,现在已经编码 6 天了。我知道我有点慢。
  • 你可以循环调用Store,直到满足某个条件,比如用户说他们什么都不买,或者类似的东西

标签: c# methods switch-statement


【解决方案1】:

立即删除 switch 之后的 return 语句,并删除自行车部分中的 2 个 return (您还需要在减去的地方设置新的 cashyo 值)。还注意到您检查的是 300,但在自行车部分减去了 3000。

返回的意思是“离开过程”,所以它不会因为你告诉它结束而循环回来。

【讨论】:

  • 非常感谢。
猜你喜欢
  • 2017-07-15
  • 2017-02-09
  • 1970-01-01
  • 1970-01-01
  • 2011-03-19
  • 2015-03-12
  • 1970-01-01
  • 2010-11-26
  • 2022-01-20
相关资源
最近更新 更多