I have this method in java I have found here.
private void pressAnyKeyToContinue() {
try {
System.in.read();
}
catch(Exception e) {}
}
The problem I have is when I want to call it several times. I use it in a method that prints a message like this:
private void keyMessage() {
System.out.print("Press any key to continue...");
pressAnyKeyToContinue();
And then I use this method here:
public void method() {
message1();
for (Class class : classes) {
keyMessage();
}
}
The problem I have is when I call the method() first it prints.
Otuput: Press any key to continue...
Then I press a key + enter. Until here all perfect but then it prints:
Output: Press any key to continue... //* times of the loop
I mean it does not let me press any key. It simply goes until the end of the loop.
Thank you for answering and sorry about my english. I know it is not good.
Standard console java simply cannot do this. All characters that are input are buffered until you press enter at which point they are all available at System.in.
So, if you loop your 'press any key' code, say, 5 times, and I type the sentence 'hello!', your code is still stuck on the first, waiting for a key. If I then hit enter, all 5 loops finish immediately, and if you were to call waitForKey later, it'd instantly return another 2 to 3 times (once for the exclamation mark, and once for the newline.. twice if on windows, because their newlines are 2 characters).
TL;DR: You can't use System.in.read()
for this. At all.
One solution is to ask the user to not press 'any' key, but to press the 'enter' key, and then use for example a scanner's next()
call after setting the delimiter to newline, or to write code that keeps calling System.in.read()
until it returns '\n':
private void pressEnterToContinue() {
while (true) {
int c;
try {
c = System.in.read();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (c == -1 || c == '\n') return;
}
}