您需要在调用in.nextLine()
行的后面立即调用in.nextInt()
,原因是仅要求下一个整数不会占用输入中的整个行,因此您需要通过调用来跳至输入中的下一个新行字符in.nextLine()
customerChoice = in.nextInt();
in.nextLine();
每次您需要在调用不消耗整行的方法后获取新行时,都必须执行此操作。考虑改用BufferedReader
对象!
BufferedReader reader = new BufferedReader(new InputStreamReader(system.in));
int integer = Integer.parseInt(reader.readLine());
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
将忽略大小写差异,这在这种情况下可能有用。