我仍然是 Java 的新手,所以如果这个问题听起来很愚蠢,请赐教。如有任何建议,我们将不胜感激。
我正在考虑某种方法来实现一个程序,该程序允许用户从键盘输入一个键来执行不同的任务。问题是,程序应该能够继续直到用户单击特定的键,比如说“X”。
这是我正在开发的 PizzaDemo 类的一部分,也是执行上述任务的 getPizzas() 方法的一部分:
public class PizzaDemo {
private PizzaOrder list;
public PizzaDemo(){
list = new PizzaOrder();
}
public static void getPizzas(){
Scanner sc = new Scanner(System.in);
System.out.println("To add a new Ham & Cheese pizza, press H.");
System.out.println("To add a new Pepperoni pizza, press P.");
System.out.println("To add a new Tropical pizza, press T.");
System.out.println("To exit, press X");
String input = sc.next();
while(!input.equalsIgnoreCase("H") && !input.equalsIgnoreCase("P") && !input.equalsIgnoreCase("T") && !input.equalsIgnoreCase("X")){
System.out.println("Invalid key. Enter again: ");
input = sc.next();
}
if (input.equalsIgnoreCase("H")){
System.out.println("Enter the size of the pizza: ");
String size = sc.next();
System.out.println("Enter the number of ham toppings: ");
int n1 = sc.nextInt();
System.out.println("Enter the number of cheese toppings: ");
int n2 = sc.nextInt();
Topping[] top = {createTopping("ham", n1), createTopping("cheese", n2)};
Pizza p = createHamCheese(size, top);
PizzaDemo demo = new PizzaDemo();
demo.list.setPizza(p);
getPizzas();
}
// the rest of the code is omitted
}
}
问题是,我似乎找不到任何方法来使用构造函数,即使调用递归(在 if block 中),仍然可以保留先前添加的元素。有人对我有什么建议吗?构造函数用于初始化新的披萨订单,它是程序的一部分,所以我不能省略它。
提前谢谢大家。
最佳答案
不要为此使用递归。您最终可能会出现堆栈溢出,这不是双关语。使用循环。
public static void getPizzas(){
Scanner sc = new Scanner(System.in);
String input;
do{
//put code in here
} while(!input.equalsIgnoreCase("X");
}
关于Java - 接受用户的不同按键来执行不同的任务,当用户单击时终止 "X",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9758389/