Shaharg
Shaharg

Reputation: 1029

Reading from keyboard and ignoring printed text

I am writing a java program (In Intellij) that accepts a command from the user and reacts to the command. The reaction is asynchronous (using a separate thread).

    Scanner in = new Scanner(System.in);
    String command = null;
    do {
        System.out.println("Enter command or q to exit: ");
        command = in.nextLine();
        System.out.println("Received "+command);
        obj.react(command);
    }while (!command.equals("q"));

The reacting object may take a while to react and prints a message after it finishes. The problem is that if I start typing a command, and before I finish, the object prints something, the typed command is lost.

For example Here is a problematic scenario (The text in italics is the user input):

Enter command or q to exit:

go

Received go

goAgainobj finished reacting!

Received

In this case, when I Hit enter after the printed message, the received command is empty.

Is there any way to keep the typed characters even after something was printed?

Upvotes: 0

Views: 61

Answers (1)

TreffnonX
TreffnonX

Reputation: 2930

If you use an actual console, printed output will not affect written input. If you type 'go' and the system prints 'Again', then the in-buffer still knows 'go'. This is unintuitive and bad to read, but it's practical to interrupt running scripts, or other programs.

This may already work on your IDE or your system, depending on OS ans IDE.

If you want something more 'pretty' then you need to fully control input and output, much like the 'top' command in linux (if you happen to know that). You can handle this way of input better with the Console class. See: https://www.codejava.net/java-se/file-io/3-ways-for-reading-input-from-the-user-in-the-console #3

The most intuitive idea to solve your problem seems to read, and then remove all input at the time you want to print something, and reprint it, so you'd get:

> go
received go
obj finished reacting!
> go
...

You'd basically always print an input line yourself, after first reading and removing the already printed input. This is why you need the Console class, because there, input and output are synchronized, so if you print something, you know that no input will happen in the meantime.

Upvotes: 1

Related Questions