Saturday 15 September 2012

java - How to clear the standard input (term) -


How to clear the standard input (word) in Java?

A little bit of history: I am writing "Reflex" program, the algorithm is very simple:

  Wait for a random quantity print "Press Enter" The line is   

, if the user accidentally enters the login key, it will be read so that the test is wrong. My goal is to fix the bug. To do this, I want an algorithm like this:

  Wait for a random amount of time to print stdin "Press Enter" read line   

but I find no way to do this: it looks interesting: available gets the number of characters remaining and leave leaving them Will give Working on paper only If you insist on an application by pressing the Enter key several times, then available method returns

An estimate of the number of bytes which Can be read (or

is left from this input stream without blocking, therefore, the return value is incorrect, at least one carriage return remains in buffer And the bug is still here.

The trick may be but this platform is up to which I Besides, calling Java a system routine is a bad idea. Also, to start over, I want to clear the standard input of my program but I do not close it. I do not want to block my program, but to give the user an input, this is a very basic problem for me, if I am ashamed, the answer is obvious! < P>

T "clear stdin" is the answer I think is OS specific, and it may not even be worth trying.

However, to solve your problem, you can use java.util.Timers which prompts the user at some random time. It will move to a different thread. When your user has entered in the end, check whether it indicates or not.

An example of the code given below will print "Enter" after 5 seconds. The main thread instantly waits for the user input, if the entry is pressed long ago it will be called because the boolean switch is not yet

  Static Boolean userpropected = false; Public Static Zero Main (string [] Args throws IOException {// Setup is a 5 seconds timer which prompts the user and switches to correct user-configured flag // It will run in a different thread timer timer = new Timer (wrong); Timer Schedule (New Timer Task) {@ Override Public Wired Run ({{System.out.println ("Press Enter"); Synchronize (timer test class) {userPrompted = true;}}}, 5000); // Blocks user input system.out.printline ("Waiting for ready .. .. as soon as you get the signal, press as soon as" ..); String input = new BufferedReader (New InputStreamReader (System.in)). ReadLine (); // Check that the user has been synchronized (Timer test class) {if (! Userprompted) System.out.println ("You entered before signaling"); Else System.out.println ("You pressed after the signal"); }}    

No comments:

Post a Comment