Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法检测System.out.print()java之后是否按下了enter键_Java - Fatal编程技术网

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

无法检测System.out.print()java之后是否按下了enter键,java,Java,我是java的初学者。任务是输入图书名称和年龄建议。按enter键时,程序将不再接受输入。这个程序只需要输入一本书。为什么会这样 Scanner scanner = new Scanner(System.in); ArrayList<Book> bookList = new ArrayList(); while(true){ System.out.print(&qu

我是java的初学者。任务是输入图书名称和年龄建议。按enter键时,程序将不再接受输入。这个程序只需要输入一本书。为什么会这样

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);
            
        }
Scanner Scanner=新的扫描仪(System.in);
ArrayList bookList=新建ArrayList();
while(true){
System.out.print(“输入书名,空停止:”);//只能输入一次
字符串行=scanner.nextLine();
if(第行等于(“”){
打破
}
系统输出打印(“输入年龄建议:”);
int line2=scanner.nextInt();
书本=新书(第行,第2行);
图书目录。添加(图书);
}

如果要在回车时中断,请使用以下命令:

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

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

    Book book = new Book(line, line2);
    bookList.add(book);
     
    if (scanner.hasNextLine())
    scanner.nextLine();
这就是它发生的原因。
使用
intline2=Integer.parseInt(scanner.nextLine())
可以解决您的问题

如果确实有效,您尝试过吗?