正如 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 点,但它应该足以让球滚动。
您可能应该重新考虑做的一件事是使用整数代码来表示浇头。使用枚举可能会使事情更容易实现。
我还注意到您添加了三种不同类型的比萨饼,我假设它们是三个单独的对象。
由于您正在循环向比萨饼添加配料,因此请创建一个抽象的比萨饼类。通过这种方式,您可以将其扩展为通用的预制比萨,例如意大利辣香肠或奶酪,并在您希望客户定制他们的订单时使用抽象比萨类。