0

I am having a bug (screenshot) with my program. I want to input a book title but the program automatically accepts 'nothing' then goes to the next line. Please see my code here:

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;

etc... and this is my addBook method

 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!");
}

this is the whole code

nyelnyelnyel
  • 27
  • 1
  • 7
  • try adding a blank input.nextLine(); after the choice.nextInt(); and see if that solves your problem. – Jay T. Feb 19 '16 at 01:50

2 Answers2

1

Check out this question and answer; it'll solve your problem:

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

Community
  • 1
  • 1
Limit
  • 11
  • 2
0

Scanners call to nextInt will only consume digits from the input stream. When the choice of 1 was inputted Scanner read the characters, "1\n" or "1\r\n" depending on the operating system, into its buffer from System.in. Then Scanner read only the characters it needed to give an int value. This leaves "\n" or "\r\n" remaining in its buffer. The next call to nextLine will read from the buffer until it encounters '\n'.

A solution is to call the nextLine method after nextInt to clear Scanner's buffer.

Change to fix the problem starting at line 27.

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