你需要打电话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 的泛型类型,以便进一步调用 theMenu.get() 不需要转换为字符串。
ArrayList<String> theMenu = new ArrayList<String>();
比较字符串时,请确保使用str.equals("string to compare with")
方法,而不是等于运算符 (==
)。因此,例如,choice2 == "yes"
应该是choice2.equals("yes")
. Using equalsIgnoreCase
代替equals
将忽略大小写差异,这在这种情况下可能有用。