Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Console Prompt for ENTER input before moving on [duplicate]

Tags:

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();     } } 
like image 867
MasonAlt Avatar asked Oct 03 '14 18:10

MasonAlt


People also ask

How do you take input until Enter is pressed in java?

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.

How to repeat an input In java?

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.


2 Answers

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(); } 
like image 185
M A Avatar answered Sep 19 '22 14:09

M A


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.

like image 33
Bruno Franco Avatar answered Sep 19 '22 14:09

Bruno Franco