I am creating a simply story, which will occasionally prompt the user to hit ENTER. It works the first time I prompt for it, but then it will immediately execute the other prompts, maybe because the program runs so fast by the time you let the ENTER key up, it already ran the check for the prompts.
Any ideas? Code Below.
System.out.println("...*You wake up*..."); System.out.println("You are in class... you must have fallen asleep."); System.out.println("But where is everybody?\n"); promptEnterKey(); System.out.println("You look around and see writing on the chalkboard that says CBT 162"); promptEnterKey(); ////////////////////////////////////////////////////// public void promptEnterKey(){ System.out.println("Press \"ENTER\" to continue..."); try { System.in.read(); } catch (IOException e) { e.printStackTrace(); } }
Using an Extra nextLine() to Wait for Enter Key in Java Scanner scans the text and parse primitive types like int and String . This class comes with a lot of methods that are used in input operations. The most commonly used methods are the nextInt() , nextLine , nextDouble , and etc.
The while loop in Java is a so-called condition loop. This means repeating a code sequence, over and over again, until a condition is met. In other words, you use the while loop when you want to repeat an operation as long as a condition is met.
The reason why System.in.read
is not blocking the second time is that when the user presses ENTER the first time, two bytes will be stored corresponding to \r
and \n
.
Instead use a Scanner
instance:
public void promptEnterKey(){ System.out.println("Press \"ENTER\" to continue..."); Scanner scanner = new Scanner(System.in); scanner.nextLine(); }
If we keep your approach of using System.in
, the right thing to do is defining the bytes you will want to read, change your prompEnterKey to this:
public static void promptEnterKey(){ System.out.println("Press \"ENTER\" to continue..."); try { int read = System.in.read(new byte[2]); } catch (IOException e) { e.printStackTrace(); } }
It will work as you need. But, as the others said, you can try different approaches like the Scanner
class, that choice is up to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With