无法检测在System.out.print()java之后是否按下了回车键



我是java的初学者。任务是输入图书名称和年龄建议。按下回车键时,程序将不再接受输入。这个程序只接受一本书的输入。为什么会出现这种情况?

Scanner scanner = new Scanner(System.in);
ArrayList<Book> bookList = new ArrayList(); 

while(true){

System.out.print("Input the name of the book, empty stops: "); //Only one input possible
String line = scanner.nextLine();
if(line.equals("")){
break;
}

System.out.print("Input the age recommendation: ");
int line2 = scanner.nextInt();

Book book = new Book(line, line2);
bookList.add(book);

}

如果您想在输入时中断,请使用以下命令:

if(line.equals(System.lineSeparator()) { break; }

它在第一行之后中断,因为scanner.nextInt();只读取数字,但由于您按enter键输入年龄而创建的换行符没有。因此循环继续,然后在下一个循环中作为空字符串进行处理。要解决它,你可以做:

Book book = new Book(line, line2);
bookList.add(book);

if (scanner.hasNextLine())
scanner.nextLine();

这就是它发生的原因。https://www.geeksforgeeks.org/why-is-scanner-skipping-nextline-after-use-of-other-next-functions/使用int line2 = Integer.parseInt(scanner.nextLine());可以解决问题

相关内容

最新更新