5

Is there a way to check if the user is typing in the console window in Java?

I want the program print whatever I type if I type something, otherwise print out "No input".

The tricky part is I want the program keep looping and printing out "No input", and then when I type "abc", it would immediately print out "abc".

I tried to use Scanner to do this as:

Scanner s = new Scanner(System.in);
while(1){
    if(s.hasNext()) System.out.println(s.next());
    else System.out.println("No input");
}

But when I ran it, if I did not type anything, the program just stuck there without printing "No input". Actually, "No input" was never printed.

gvlasov
  • 18,638
  • 21
  • 74
  • 110
Michelle
  • 51
  • 3

1 Answers1

1

From a command line, I see no chance to receive the input before hitting the "enter button". (unlike "onKeyDown/Up")

But considering & accepting this restriction, a simple solution is to use Reader.ready():

(..returns) True if the next read() is guaranteed not to block for input, false otherwise.

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Scanner;

public class Solution {

    public static void main(String[] args) throws IOException {
        final Reader rdr = new InputStreamReader(System.in);
        final Scanner s = new Scanner(rdr);
        while (true) {
            if (rdr.ready()) {
                System.out.println(s.next());
            } else {
                // use Thread.sleep(millis); to reduce output frequency
                System.out.println("No input");
            }
        }
    }
}
xerx593
  • 12,237
  • 5
  • 33
  • 64