我是编程新手,尤其是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循环,设置它如果用户输入!= to“quit”,那么它就会运行。
对我来说困难的是我不知道如何让我的程序考虑用户输入的两个不同部分,“汉堡包3”并总结最后的数字部分。
最后,我希望它能说出“你今天卖了X汉堡包,Y沙拉和Z特价。”
帮助将不胜感激。
答案 0 :(得分:1)
您可能希望使用三个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中类的引用
答案 1 :(得分:0)
这两种方法应该是您正在寻找的。 p>
用于拆分:String.split(String regex) http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
用于将String解析为Interger:Integer.parseInt(String s) http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
答案 2 :(得分:0)
您可以使用input.split(" ")
拆分字符串。此方法为您提供两个字符串 - 主字符串的两个部分。用字符串" "
分割的字符将不再出现在字符串中。
要从字符串中获取整数,可以使用静态方法Integer.parseInt(inputPartWithCount)
。
我希望这有帮助!