Java Console Prompt for ENTER input before moving on

Java Console Prompt for ENTER input before moving on

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.

Java Console Prompt for ENTER input before moving on

Leave a Reply

Your email address will not be published.