-3

I am a beginner in java. The task is to enter a books name and age recommendation. When pressing enter the program should no longer take input. The program just takes input for one book. Why is this the case?

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);
            
        }
OgOger
  • 3
  • 3

3 Answers3

0

If you want to break on enter, use this:

if(line.equals(System.lineSeparator()) { break; }
Rafay
  • 80
  • 8
0

It's breaking after the first line because scanner.nextInt(); only reads the number, but the newLine created because of you pressing enter to enter the age was not. So the loop continues and then it gets processed on the next loop as an empty string. To solve it you could do:

    Book book = new Book(line, line2);
    bookList.add(book);
     
    if (scanner.hasNextLine())
    scanner.nextLine();
PabloBuendia
  • 267
  • 1
  • 11
-1

This is why it happened. https://www.geeksforgeeks.org/why-is-scanner-skipping-nextline-after-use-of-other-next-functions/ Using int line2 = Integer.parseInt(scanner.nextLine()); can solve your problem

judaikun88
  • 59
  • 5