Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if the user is typing in the console window

Tags:

java

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.

like image 947
Michelle Avatar asked Nov 10 '22 18:11

Michelle


1 Answers

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");
            }
        }
    }
}
like image 111
xerx593 Avatar answered Nov 14 '22 22:11

xerx593