Java 错误:在没有输入的情况下输入自动转到下一行

Java Bug: Input automatically go to next line without input yet

我有一个 bug(截图) 用我的程序。我想输入书名,但程序自动接受 'nothing' 然后转到下一行。请在此处查看我的代码:

System.out.println("Book Management System");
System.out.println("1. Add book");
System.out.println("2. Delete book");
System.out.println("3. Update book information");
System.out.print("Enter your choice: ");
        choice = input.nextInt();

        switch (choice)
        {
            case 1:
                System.out.println("Add a new book");
                System.out.print("Enter title: ");
                book_title = input.nextLine();
                System.out.print("Enter author: ");
                book_author = input.nextLine();
                System.out.print("Enter publisher: ");
                book_publisher = input.nextLine();
                addBook(connection, preparedStatement, book_title, book_author, book_publisher);
                break;

等等...这是我的 addBook 方法

 public static void addBook(Connection connection, PreparedStatement preparedStatement, String name, String author, String publisher) throws SQLException{
    preparedStatement = connection.prepareStatement("INSERT INTO books.book_info (book_title, book_author, book_publisher) VALUES (?,?,?)");
    preparedStatement.setString(1, name);
    preparedStatement.setString(2, author);
    preparedStatement.setString(3, publisher);
    preparedStatement.executeUpdate();
    System.out.println("Book added!");
}

这是全部code

对 nextInt 的扫描程序调用将仅使用输入流中的数字。当输入选项 1 时,扫描器从 System.in 读取字符“1\n”或“1\r\n”,具体取决于操作系统。然后 Scanner 只读取它需要给出一个 int 值的字符。这会将 "\n" 或 "\r\n" 保留在其缓冲区中。对 nextLine 的下一次调用将从缓冲区中读取,直到遇到 '\n'。

解决办法是在nextInt之后调用nextLine方法来清除Scanner的buffer。

更改以修复从第 27 行开始的问题。

choice = input.nextInt();
input.nextLine(); //clear new line character left over from input.

查看此问答;它会解决你的问题:

Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods