Tuesday, 24 January 2017

Java Console Prompt for ENTER input before moving on





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();

}
}

Answer



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();
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...