我对编程非常陌生,尤其是Java。我需要创建一个程序,计算一个餐厅的每个条目被订购的订单数量。该餐厅有3个条目,汉堡包,沙拉和特色菜。
我需要设置程序,以便用户输入“汉堡3”,它会跟踪该数字并将其加到最后。如果用户输入“退出”,则程序将退出。
System.out.println("Enter the type (special, salad, or hamburger) of entrée followed by the number, or quit to exit the program.");
我正在考虑使用while循环,将其设置为如果用户输入!=为“退出”,则它将运行。
对我来说困难的是,我不知道如何使程序考虑用户输入的两个不同部分“汉堡包3”,并在最后总结数字部分。
最后,我要说的是“今天您卖了X个汉堡包,Y个色拉和Z个特色菜”。
帮助将不胜感激。
您可能希望将三个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
为此轻松地使用。见该Scanning
教程
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");
}
看一下if-then和if-then-else语句以及while和do-while语句以获取更多详细信息。
您可能还会发现“学习Java语言”有一些帮助。另外,请保留一份JavaDocs副本,这将使它易于在API中找到对类的引用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句