• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

getch() in Java?

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

Trombe

Member
Joined
Mar 13, 2005
Location
Austin, Texas
I'm writing an application and I need to be able to pause execution while the program waits for the user to press ENTER.
(Press Enter to Continue...)

Right now I'm using a crutch- I wait for the user to press the letter C.
Code:
        public void waitForCont()
        {
                out.printf("\nPress C to Continue...\n");
                boolean pressed = false;
                String entered = "";
                while(!pressed)
                {
                        entered=kb.next();
                        if((entered.equals("C"))||entered.equals("c"))
                            pressed=true;
                }
          }

It would be wonderful if there was a Java equivalent to the getch() function from C.
 
The system input stream (System.in) has a number of methods available to it. I haven't done any checking of the following code, but it's what I immediatly thought of:

Code:
public void waitForKeypress() {
   while( System.in.read() != (int)'c' ) {
      Thread.sleep(100); //Let the CPU do more worthwhile things for 0.1 seconds ;)
   }
}

The only problem I can think of is that the stream may need to be flushed before this will work, but the javadoc says that System.in.available() (to find the number of bytes remaining in the stream) will allways return 0, so perhaps not.

JigPu
 
Called readString()... or others, more than one way to do it. What are the types of objects you have there?
 
If you're doing commandline input you should use the scanner class:

import java.util.Scanner

The method would then look something like this:

public void waitForCont()
{
Scanner keyboard = new Scanner(System.in);

System.out.println("press enter to continue")

keyboard.next();
}

If not, you could just replace the "C" with the next line "\n" character encoding. This is the string that the enter key usually returns.
 
I was using a scanner actually, it was delcared earlier since it's used for many methods.

JigPu really put me on the right track with the System.in

This works perfectly:

Code:
	void pause() 
	{
		try
		{
			out.printf("\n\n  Press ENTER..");
			System.in.read();
		}
		catch(IOException exe)
		{
			out.printf("Error?");
		}
	}
 
Back