0

我需要创建一个 java 应用程序,在每个问题后询问用户是否要继续。

例如,你叫什么名字?你要继续吗?Y/N 你想点什么披萨?

到目前为止我的代码是这样的,但我不知道在 if 循环中放置什么

public class Mod2P5{
public static void main(String[]args){

  while(true){


 Double cost = 0.00;
 String cont = "Y";
 /*Start of Menu*/
String pizza_item[] = new String [13];
pizza_item [0] = "Hawian";
pizza_item [1] = "Meat Lovers";
pizza_item [2] ="Vege";
pizza_item [3] = "Supreme";
pizza_item [4] = "Pepironi";
pizza_item [5] = "God Father";
pizza_item [6] ="Mr Wedge";
pizza_item [7] = "Double Bacon Cheese Burger";
pizza_item [8] = "Mustard Beef and Bacon";
pizza_item [9] ="Chilly Beef";
pizza_item [10] = "BBQ";
pizza_item [11] = "Sweet and Sour";
pizza_item [12] = "Prawn";
Double pizza_price[] = new Double [13];
pizza_price [0] =8.50;
pizza_price [1] = 8.50;
pizza_price [2] =8.50;
pizza_price [3] = 8.50;
pizza_price [4] =8.50;
pizza_price [5] = 8.50;
pizza_price [6] =8.50;
pizza_price [7] =8.50;
pizza_price [8] = 13.50;
pizza_price [9] =13.50;
pizza_price [10] = 13.50;
pizza_price [11] =13.50;
pizza_price [12] = 13.50;
 /*End of Menu*/ 


int pickup_delivery = readInt("Press 1 for delivery or 2 for pickup.");
cont = readString("Press Y to continue or N to cancel.");
String name = readString("What is your name");
cont = readString("Press Y to continue or N to cancel.");

  System.out.print(pickup_delivery + name + cost);

  if (cont.equalsIgnoreCase("Y")){
        break; 
// goes to beginning of while loop
  }
  }


}


/*reads and returns an integer from the keyboard*/
public static int readInt(String prompt){
System.out.println(prompt);
java.util.Scanner keyboard = new java.util.Scanner(System.in);
return keyboard.nextInt();
}
/*reads and returns a String from the keyboard*/
public static String readString(String prompt){
System.out.println(prompt);
java.util.Scanner keyboard = new java.util.Scanner(System.in);
return keyboard.nextLine();
}
/*reads and returns a double from the keyboard*/
public static double readDouble(String prompt){
System.out.println(prompt);
java.util.Scanner keyboard = new java.util.Scanner(System.in);
return keyboard.nextDouble();
}

}
4

3 回答 3

2

你可以这样做:

while(true) {
    // initialization

    int pickup_delivery = readInt("Press 1 for delivery or 2 for pickup.");
    cont = readString("Press Y to continue or N to cancel.");

    if (cont.equalsIgnoreCase("n"))
        continue; // goes to beginning of loop; restarts the questionaire
}

要退出循环,只需使用break;.

于 2012-07-30T03:14:49.227 回答
2

一件事可能会让你失望 -

if (cont=="n"){ //<-- this wont work 
  System.exit();
}

比较String对象时,您需要使用equals()方法 - 而不是==运算符。操作员将==比较参考,String例如,这并不意味着内容。

@Zong Li 在这种情况下提到了一个更好的选择 - 使用equalsIgnoreCase()它将使您的程序更加用户友好。

于 2012-07-30T03:42:22.700 回答
-1

因为这是家庭作业,所以请使用Head First Design Pattern学习设计模式,这是理解对象的最简单方法。(或其他一些书籍或教程)

他们讲述了披萨,以及如何做有良好的做法......你会发现重启是如何工作的!

于 2012-07-30T06:53:29.920 回答