由于某些原因,我的代码将不接受最后一行“您想订购的商品:”的输入
谁能告诉我我的错误在这里吗?它正在正确地编译一切。我只是一个初学者,所以请简单地告诉我。
import java.util.Scanner; import java.util.*; class RestaurantMain { public static void main(String[] args) { //Create an array list ArrayList menu = new ArrayList(); //Variables// int choice; int customerChoice; boolean trueFalse; int restart = 0; String choice2; String addItems = ""; int menuCount = 0; int indexCount = 0; String item = ""; //Import input device Scanner in = new Scanner(System.in); ArrayList theMenu = new ArrayList(); System.out.println("Welcome to the Cooper's restaurant system!"); System.out.println("How can I help?"); System.out.println(""); System.out.println("1. Customer System"); System.out.println("2. Management System"); System.out.println(""); System.out.println(""); System.out.print("Which option do you choose: "); choice = in.nextInt(); if (choice == 1) { System.out.println("Our menu's are as follows:"); System.out.println(""); System.out.println("1. Drinks"); System.out.println("2. Starters"); System.out.println("3. Mains"); System.out.println("4. Desserts"); System.out.println(""); System.out.println("Please note - You MUST order 5 items."); System.out.println(""); System.out.print("What menu would you like to follow? "); customerChoice = in.nextInt(); if (customerChoice == 1) { System.out.println("Drinks Menu"); System.out.println("Would you like to order? "); choice2 = in.nextLine(); if (choice2 == "yes") { System.out.println("Please enter the amount of items you want to order: "); while (indexCount <= menuCount); System.out.println("Please enter your item: "); item = in.nextLine(); { theMenu.add(item); } } } if (customerChoice == 2) { System.out.println("Starters Menu"); } if (customerChoice == 3) { System.out.println("Mains menu"); } if (customerChoice == 4) { System.out.println("Desserts Menu"); }
您需要在调用in.nextLine()行的后面立即调用in.nextInt() ,原因是仅要求下一个整数不会占用输入中的整个行,因此您需要通过调用来跳至输入中的下一个新行字符in.nextLine()
in.nextLine()
in.nextInt()
customerChoice = in.nextInt(); in.nextLine();
每次您需要在调用不消耗整行的方法后获取新行时,都必须执行此操作。考虑改用BufferedReader对象!
BufferedReader
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int integer = Integer.parseInt(reader.readLine());
Scanner.nextInt()如果无法将输入解析为整数,则会引发相同的错误。
Scanner.nextInt()
关于您对错误的评论,有以下一种:
while (indexCount <= menuCount); System.out.println("Please enter your item: "); item = in.nextLine(); { theMenu.add(item); }
}
相反,应如下所示:
while(indexCount <= menuCount){ System.out.println("Please enter your item: "); item = in.nextLine(); theMenu.add(item); }
另外,这也不是绝对必要的,但是我建议您在实例化列表时确实声明ArrayList的泛型类型,这样就不必将对Menu.get()的进一步调用强制转换为String了。
ArrayList<String> theMenu = new ArrayList<String>();
比较字符串时,请确保使用str.equals("string to compare with")方法,而不是等于运算符(==)。因此,例如,choice2 == "yes"应该改为choice2.equals("yes")。使用equalsIgnoreCase代替代替equals将忽略大小写差异,这在这种情况下可能有用。
str.equals("string to compare with")
==
choice2 == "yes"
choice2.equals("yes")
equalsIgnoreCase
equals