8

Is there any equivalent to C++’s getch() in Java? That is a function that moves the control forward as soon as a keyboard key is pressed, and also stores the character pressed.

I would like to use that function in a console app.

Kamran Ahmed
  • 11,809
  • 23
  • 69
  • 101

3 Answers3

5

There's no getch() function equivalent in java. But since you are not the first one who is asking about it, there are some solutions available:

I think nothing has changed since then - I mean, no new getch() alike functions were added to Java.

Community
  • 1
  • 1
Qiu
  • 5,651
  • 10
  • 49
  • 56
2

There's no getch() function equivalent in java.

You have to create a GUI and attach the Event Listener's to them .

EDIT:How can I read input from the console using the Scanner class in Java?

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

You can use casting and get a character value from the console directly.

public class TestConsole
{
    public static void main(String[] args)
    {
        System.out.print("Enter a character: ");
        // Read the char
        char ch = (char) System.in.read();

        System.out.print("\n You pressed: " + ch);
    }
}

It's working. See this demo online. http://ideone.com/RZ6vhK

Sri Harsha Chilakapati
  • 11,744
  • 6
  • 50
  • 91