Alexey  Usharovski
Alexey Usharovski

Reputation: 1442

nextLine(), hasNextLine() and NoSuchElementException from java Scanner class

If we are making console input with Scanner we have two ways how to write input cycle

1.

    Scanner scanner = new Scanner(System.in);
    while (true) {
        System.out.println(scanner.nextLine());
    }

2.

    Scanner scanner = new Scanner(System.in);
    while (scanner.hasNextLine()) {
        System.out.println(scanner.nextLine());
    }

I believe second one is more correct also because that's mentioned in hasNextLine() javadoc that this method is waiting for new line. But why the first one is also works and waiting for a new line without NoSuchElementException?

Upvotes: 0

Views: 107

Answers (1)

user31601
user31601

Reputation: 2610

Your first solution will throw an exception when the end of the input has been reached (e.g. when the user presses Ctrl+D on linux, or when you pipe a file into the input and we get to the end of the file). The second solution will exit gracefully.

If you only ever use the interactive command line, and you never send an end-of-file signal, there's no difference.

Upvotes: 1

Related Questions