-1

I'm working on simple Library Book Log system. I try add book and delete book from system. But I have a proplem in there. When I try to start program. Program is printing next line before scanning book name. How I can fix it?

if(x==1)
        {
            operation.addBook();
        }

 String[] bookshelf = new String[1000];



        //METHODS
        public void addBook()
        {
            Scanner scan = new Scanner (System.in);
            System.out.println("Enter shelf number which you want to add book: " );
            int a = scan.nextInt();


            if (bookshelf[a-1]==null)
            {
                System.out.print("Enter book's name which you want to add: ");
                bookshelf[a-1] = scan.nextLine();


                System.out.println(bookshelf[a-1] + " added to shelf " + a + " successfully");
            }

            else
            {
                System.out.println("This shelf full already");
            }
        }

OUTPUT:

Welcome to LibrarySystem
1-Add book
2-Borrow book
Choose operation number what you want: 1
Enter shelf number which you want to add book: 
1
Enter book's name which you want to add:  added to shelf 1 successfully
sancaryum
  • 11
  • 4
  • Possible duplicate of [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Savior Mar 26 '18 at 17:46
  • call scan.nextLine() right after you set a and before the if to clear out the end of line character – RAZ_Muh_Taz Mar 26 '18 at 17:46
  • https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo – TheFlyBiker 420 Mar 26 '18 at 17:48

1 Answers1

-1
  • Have two separate scanner objects to handle integer and string.
  • Fire a blank Scanner.nextLine call after Scanner.nextInt or Scanner.nextFoo to consume rest of that line including newline
  • Or, it would be even better, if you read the input through Scanner.nextLine and convert your input to the proper format you need. For examples, to an integer using Integer.parseInt(String) method.
TheFlyBiker 420
  • 37
  • 1
  • 12