Java: Enter to continue

Discussion in 'Mac Programming' started by pknz, Jun 9, 2007.

  1. pknz macrumors 68020

    pknz

    Joined:
    Mar 22, 2005
    Location:
    NZ
    #1
    In Java how do you make a program pause, ie wait for the user to hit the enter key before continuing?

    Googling showed some complicated way with readbuffers etc but that is too advanced for me at the moment, is there a simple way of doing this?

    Thanks
     
  2. hawaiian macrumors member

    hawaiian

    #2
    Hi! There is a simpler way if you are using versions of Java 1.5 or higher. It's called the Scanner class and it is located in the java.util package.

    Code:
    ...
    Scanner console = new Scanner(System.in);
    System.out.print("You're next guess? ");
    String guess = console.next();
    ...
    
    I think that's the general idea. Of course you'll want to use a loop to do some basic error checking just in case the user gives you some nasty data or something. Look up the Scanner definition at the java website. It states all the methods that it uses.

    Hope this helps or leads you in the right direction...
     
  3. BALANCEDMAN macrumors newbie

    Joined:
    Nov 12, 2008
    #3
    If using scanners. try this out.

    Prior to your system.out.println("Press enter to continue");
    you have used a line of code that says nextInt() or nextLine() or something to that effect. To fix this problem use the following code:

    Scanner keyIn = new Scanner(System.in);

    System.out.print("Press the enter key to continue");
    keyIn.nextLine();
    keyIn.nextLine();

    the first keyIn.nextLine will end the nextInt() or nextLine that was used before the System.out line and the 2nd will tell your code to continue onto the next portion.

    Hope this was clear enough
     

Share This Page