6

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
  • 9,682
  • 18
  • 56
  • 96

3 Answers3

3

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
  • 10,962
  • 6
  • 46
  • 87
3

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,222
  • 10
  • 45
  • 53
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
  • 114,879
  • 36
  • 179
  • 284