gpt4 book ai didi

java - 分解单个用户输入并将其存储在两个不同的变量中。 ( java )

转载 作者:行者123 更新时间:2023-12-01 11:55:23 26 4
gpt4 key购买 nike

我对编程非常陌生,尤其是 Java。我需要创建一个程序来计算餐厅每个条目的订单数量。餐厅有3种菜品,汉堡、沙拉、特色菜。

我需要设置我的程序,以便用户输入“hamburger 3”,它会跟踪数字并在最后将其相加。如果用户输入“quit”,程序就会退出。

System.out.println("Enter the type (special, salad, or hamburger) of entrée followed by the number, or quit to exit the program.");

我正在考虑使用 while 循环,将其设置为如果用户输入 != 为“退出”,那么它将运行。

对我来说困难的是我不知道如何让我的程序考虑用户输入“hamburger 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 来实现此目的。请参阅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 StatementsThe while and do-while Statements了解更多详情。

您还可以找到Learning the Java Language的一些帮助。另外,请保留 JavaDocs 的副本现在,它将使您更容易在 API 中找到对类的引用

关于java - 分解单个用户输入并将其存储在两个不同的变量中。 ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28493417/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com