您可能希望使用三个 int 变量作为订单数量的运行记录:
public class Restaurant {
private int specials = 0;
private int salads = 0;
private int hamburger = 0;
然后您可以使用do-while 循环向用户请求信息...
String input = null;
do {
//...
} while ("quite".equalsIgnoreCase(input));
现在,您需要某种方式来要求用户输入。为此,您可以轻松地使用java.util.Scanner。见the Scanning tutorial
Scanner scanner = new Scanner(System.in);
//...
do {
System.out.println("Enter the type (special, salad, or hamburger) of entrée followed by the number, or quit to exit the program.");
input = scanner.nextLine();
现在您有了来自用户的输入,您需要做出一些决定。您需要知道他们是否输入了有效的输入(主菜和金额)以及他们是否输入了可用选项...
// Break the input apart at the spaces...
String[] parts = input.split(" ");
// We only care if there are two parts...
if (parts.length == 2) {
// Process the parts...
} else if (parts.length == 0 || !"quite".equalsIgnoreCase(parts[0])) {
System.out.println("Your selection is invalid");
}
好的,所以我们现在可以确定用户输入是否满足或不满足第一个要求([text][space][text]),现在我们需要确定这些值是否真的有效......
首先,让我们检查一下数量...
if (parts.length == 2) {
// We user another Scanner, as this can determine if the String
// is an `int` value (or at least starts with one)
Scanner test = new Scanner(parts[1]);
if (test.hasInt()) {
int quantity = test.nextInt();
// continue processing...
} else {
System.out.println(parts[1] + " is not a valid quantity");
}
现在我们要检查是否实际输入了有效的主菜...
if (test.hasInt()) {
int quantity = test.nextInt();
// We could use a case statement here, but for simplicity...
if ("special".equalsIgnoreCase(parts[0])) {
specials += quantity;
} else if ("salad".equalsIgnoreCase(parts[0])) {
salads += quantity;
} else if ("hamburger".equalsIgnoreCase(parts[0])) {
hamburger += quantity;
} else {
System.out.println(parts[0] + " is not a valid entree");
}
查看The if-then and if-then-else Statements 和The while and do-while Statements 了解更多详情。
您还可以找到Learning the Java Language 的一些帮助。另外,请保留一份JavaDocs 的副本,这样可以更轻松地在 API 中找到对类的引用