3

我无法在循环中实现 Y/N 或 y/n。我设计它的方式是用户可以在循环中使用 Y 和 N 的大写和小写字母作为答案。顺便说一下,这是我的代码,但似乎无法使其工作:

do
        {
            Console.WriteLine("\nSelect additional topping/s\n");

            Console.WriteLine("1 - Extra meat: 200");
            Console.WriteLine("2 - Extra cheese: 100");
            Console.WriteLine("3 - Extra veggies: 80\n");

            int selectedTopping = Convert.ToInt32(Console.ReadLine());

            switch (selectedTopping)
            {
                case 1:
                    pizza = new MeatToppings(pizza);
                    break;

                case 2:
                    pizza = new CheeseToppings(pizza);
                    break;

                case 3:
                    pizza = new VeggieToppings(pizza);
                    break;

                default:
                    break;
            }

            Console.WriteLine("\nAdd more toppings? Y/N");
            

        }

        while ((Console.ReadLine() == "Y") || (Console.ReadLine() == "y"));
4

6 回答 6

6

Try to use String.Equals and StringComparison:

String.Equals(Console.ReadLine(), "y", StringComparison.CurrentCultureIgnoreCase);

from MSDN:

CurrentCultureIgnoreCase: Compare strings using culture-sensitive sort rules, the current culture, and ignoring the case of the strings being compared.

OrdinalIgnoreCase: Compare strings using ordinal sort rules and ignoring the case of the strings being compared.

于 2013-01-15T07:00:38.183 回答
6
while ((Console.ReadLine() == "Y") || (Console.ReadLine() == "y"));

ReadLine()由于您要调用两次,因此这将读取 2 行不同的行。您需要调用一次并保存该值。

于 2013-01-15T06:56:56.783 回答
6

You can use ToUpper

while ((Console.ReadLine().ToUpper() == "Y") );
于 2013-01-15T06:57:10.817 回答
5

To check Y or y ignoring case, you should use string.Equals(string,StringComparison) overload.

while (Console.ReadLine().Equals("Y", StringComparison.InvariantCultureIgnoreCase));

Please see the The Turkish İ Problem and Why You Should Care before using ToUpper or ToLower for string comparison with ignore case.

Your current code is reading the lines from console twice, that is why your code is holding up for the 2nd value.

于 2013-01-15T07:02:07.297 回答
1

正如 Austin 刚刚指出的那样,您在 while 循环语句中使用了两次 ReadLine。

值得一提的是尽量遵循模块化规则,这将有助于加快实现和调试我们的代码。

自从我进行任何 C# 编程以来已经有一段时间了,所以用 Java 风格对其进行 sudo 编码。

由于它是命令行编程,因此您可能必须多次验证用户输入。我要做的一件事是创建一个实用程序类来包含常见的用户输入任务。

public class TerminalUtil {
    private TerminalUtil() {}

    public static boolean isYes(String msg){ return (msg.ToUpper() == "Y" || msg.ToUpper() == "YES"); }
    public static boolean isNo(String msg){ return (msg.ToUpper() == "N" || msg.ToUpper() == "NO"); }
   // You also might want basic conditionals to check if string is numeric or contains letters.

    // I like using recursion for command line utilities so having a method that can re-print messages is handy
    public static void display(String[] messages){
        for(String msg : messages){
            Console.WriteLine(msg);
        }
    }

    public static boolean enterYesOrNo(String[] messages, String[] errorMessages){
        display(messages)
        String input = Console.ReadLine();
        if( isYes(input) ){
            return true;
        } else if( isNo(input) ){ 
            return false; 
        } else {
             display(errorMessages); // Maybe something like, you didn't enter a yes or no value.
             enterYesOrNo(messages, errorMessages); // Recursive loop to try again.
        }

    }
}

这是订购披萨的代码可能看起来像这样

public class OrderPizza{
    public static int selectToppings(){
        String[] message = new String[4];
        message[0] = ("\nSelect additional topping/s\n");
        message[1] = ("1 - Extra meat: 200");
        message[2] = ("2 - Extra cheese: 100");
        message[3] = ("3 - Extra veggies: 80\n");

       int option =  TerminalUtils.entryNumeric(message, {"You entered an non-numeric character, try again"} );
       if( option > 0 && option <= 3 ){
           return option;
       } else {
          Console.WriteLine("Number must be between 1 - 3, try again.");
          return selectToppings();
       }
    }

    public static Pizza order(){
        Pizza pizza = new Pizza();

        while(true){
            int toppingCode = selectTopping();
            pizza.addTopping(toppingCode);
            if(!TerminalUtil.enterYesOrNo({"\nAdd more toppings? Y/N"}, {"Please enter a 'Y'es or 'N'o"}) ){
                break;
            }
        }
    }
}

这样做的主要好处是减少了 while 循环的业务逻辑,您可以重用 TerminalUtils 中的代码。此外,这绝不是一个优雅的解决方案,我很懒,现在是 IRL 凌晨 3 点,但它应该足以让球滚动。

您可能应该重新考虑做的一件事是使用整数代码来表示浇头。使用枚举可能会使事情更容易实现。

我还注意到您添加了三种不同类型的比萨饼,我假设它们是三个单独的对象。

由于您正在循环向比萨饼添加配料,因此请创建一个抽象的比萨饼类。通过这种方式,您可以将其扩展为通用的预制比萨,例如意大利辣香肠或奶酪,并在您希望客户定制他们的订单时使用抽象比萨类。

于 2013-01-15T07:49:53.580 回答
0

我没有找到比以下更好的方法:

while ( str!="N" )
{
    str = Console.ReadLine();
    str = str.ToUpper();
    if (str == "Y");
       break;
};
于 2015-04-15T23:30:11.340 回答