How to Empty Sytem.in

A

Alvaro Puente

Hi all!

I'm writing a program in which I want to stop execution until user press
Enter.
The program works fine if user press Enter only once but, if pressed more
than once,
the next time the program asks for user input, the execution does not stop.

I guess it is because there are a few entries in the System.in buffer, so
program does
not block waiting for user entry since there are entries already in the
buffer.
I'd like to delete all those entries before doing readLine(), which will
block until
user press enter.

Do you know how can I empty System.in buffer?

Thanks a lot/Alvaro
 
F

fabio

Alvaro said:
Hi all!

I'm writing a program in which I want to stop execution until user press
Enter.
The program works fine if user press Enter only once but, if pressed more
than once,
the next time the program asks for user input, the execution does not
stop.

I guess it is because there are a few entries in the System.in buffer, so
program does
not block waiting for user entry since there are entries already in the
buffer.
I'd like to delete all those entries before doing readLine(), which will
block until
user press enter.

Do you know how can I empty System.in buffer?

This work:

/////////////////////////////////////////////////
import java.io.IOException;

public class sys {
public static void main(String args[]) {

for (int k=0; k<2; k++) { // 2 times

System.out.print("Hit a key"); // prompt

try {
System.in.read(); // user write anything
}
catch (IOException e) {

}

//clear the buffer ---------------------
try {
while(System.in.read()!='\n');
}
catch (IOException e) {

}

}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top