您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Java输入不起作用(初学者)

Java输入不起作用(初学者)

您需要在调用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将忽略大小写差异,这在这种情况下可能有用。

java 2022/1/1 18:25:33 有441人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶