Julius
Julius

Reputation: 1

How to read a String from console? NoSuchElementException: No line found

I have to implement the interface Terminal, which has two methods. The first method is just a simple output and it works fine. The goal of the second method is to read the input from the user via console and return a splitted (whitespaces) array.

public class GameTerminal implements Terminal {

    @Override
    //output method

    @Override
    public String[] readInput() {
        Scanner scn = new Scanner(System.in);
        String input = scn.nextLine();
        return input.trim().split("\\s+");
    }

}

This code throws a Exception:

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Scanner.java:1540)
    at student.GameTerminal.readInput(GameTerminal.java:20)
    ...

I tried to fix the problem with using scn.next(), scn.hasNext(), scn.hasNextLine() and a BufferedReader, but nothing works. I have no second Scanner and i don't use scn.close().

The code runs with gradle in IntelliJ.

Has anabody a solution or idea? Thank you!

Upvotes: 0

Views: 83

Answers (1)

Allen D. Ball
Allen D. Ball

Reputation: 2026

I think all you have to do is use the same Scanner between calls to preserve state:

public class GameTerminal implements Terminal {
    private Scanner scn = new Scanner(System.in);
    ...
    public String[] readInput() {
        String input = scn.nextLine();
        return input.trim().split("\\s+");
    }
}

A simple driver:

public class Example {
    public static void main(String[] args) throws Exception {
        GameTerminal terminal = new GameTerminal();
        String[] tokens = null;

        while ((tokens = terminal.readInput()) != null) {
            System.out.println(Arrays.toString(tokens));
        }
    }
}

Test run:

$(/usr/libexec/java_home -v 11)/bin/java Example.java
some tokens
[some, tokens]
some more tokens
[some, more, tokens]

Upvotes: 1

Related Questions