0

I am a beginner programmer student from Finland, this is my first post here so hello everyone! So, I am writing this Java program that reads user inputs and creates new Books according to the inputs and then adds them to list and sorts them according to their recommended ages and names. The following code doesn's seem to work, the loop breaks automatically after one go. I actually fixed the issue using "Integer.valueOf" instead of nextInt but I started wondering why the nextInt doesn't work here?

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);
    ArrayList<Book> books = new ArrayList<>();

    while (true) {
        System.out.println("Enter books name, blank will end the loop:");
        String bookName = reader.nextLine();
        if (bookName.equals("")) {
            break;
        }

        System.out.println("Enter the books recommended age:");
        int minimAge = reader.nextInt();
        Book book = new Book(bookName, minimAge);
        books.add(book);

    }

    System.out.println("Total " + books.size() + " books.");
    System.out.println();
    System.out.println("Books:");
    
    Comparator<Book> vertaus = Comparator
            .comparing(Book::getMinimAge)
            .thenComparing(Book::getName);

    
    Collections.sort(books, vertaus);
    for (Book k : books) {
        System.out.println(k);
    }

}

}

  • 1
    Just a friendly reminder: `Java != JavaScript` ;) – MauriceNino Aug 05 '20 at 11:34
  • Ahh yes thank you :) – SeppoHyvarinen Aug 05 '20 at 11:36
  • 3
    Because `nextInt` will only read a number but not the end-of-line character that you also entered by pressing the Enter key after the number, and then when the loop runs again the line `String bookName = reader.nextLine();` will read the end-of-line character and then it thinks it has just read an empty line and breaks out of the loop. – Jesper Aug 05 '20 at 11:37
  • By the way, questions about how Java's `Scanner` class works are very common on StackOverflow, if you search you'll find many answers to similar questions. – Jesper Aug 05 '20 at 11:39
  • I see, thanks for the answer! – SeppoHyvarinen Aug 05 '20 at 11:39

1 Answers1

0

While entering number for minimAge when you press enter, the scanner takes two input, the number and a EOF character. As a result EOF character is set as the next bookname. Which is equivalent to empty string and breaks the loop. To skip this add the following code

int minimAge = reader.nextInt();
reader.nextLine();
mahfuj asif
  • 824
  • 3
  • 17