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

时间:2021-04-05 03:44:07

标签: 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);
            
        }

3 个答案:

答案 0 :(得分:0)

如果您想在输入时中断,请使用:

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

答案 1 :(得分:0)

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

    Book book = new Book(line, line2);
    bookList.add(book);
     
    if (scanner.hasNextLine())
    scanner.nextLine();

答案 2 :(得分:-1)

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

相关问题