0

At the first loop while stops and waits for console input at the incomStr = view.read(); but at the second loop it doesn't stop, reads null and goes on.

Why is it happening?

public void mainDialogueHolder() {//todo

        setCmdState(CmdLineState.WAIT);
        view.write("Hello, user!");
        view.write("Please, type `help` for list available commands. ");
        while (getCMDState().equals(CmdLineState.WAIT)){
            String incomStr;
            incomStr = view.read();//implementation is below
            readCmd(incomStr);
        }
    }

Implementation of view

public class Console implements View {

    @Override
    public void write(String message) {
        System.out.println(message);
    }

    @Override
    public String read() {
        try (
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))
        ){
            return reader.readLine();
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
            return null;
        }
    }
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95

1 Answers1

0

Well it looks like your try with resource closes the System.in by closing the BufferedReader, which in turn will close it's Reader (InputStreamReader) and that one closes System.in. The System.in is final static, hence once you close it you wouldn't be able to use it again as it's not possible to reopen it. Well what do I do then If I can't close it ? Perhaps you could write a wrapper like it was suggested here In Java is it possible to re-open System.in after closing it