Check if user is typing console window

Is there a way to check if a user types in a console window in Java?

I want the program to print everything that I type, if I print something, otherwise I will print "Without input".

The tricky part is that I want the program to continue to cycle and print "No input", and then when I type "abc", it immediately displays "abc".

I tried using Scanner for this:

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 started it, if I didnโ€™t type anything, the program simply got stuck there without printing โ€œWithout inputโ€. In fact, "No Input" was never printed.

+5
source share
1 answer

From the command line, I see no way to get input before I press the "enter button". (unlike "onKeyDown / Up")

But, given and accepting this limitation, a simple solution is to use Reader.ready () :

(.. returns) True if the next read() guaranteed not to block the 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"); } } } } 
+1
source

Source: https://habr.com/ru/post/1214825/


All Articles