Is there any equivalent of getch() from C++ in Java? [duplicate]

你离开我真会死。 提交于 2020-12-08 07:16:41

问题


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.


回答1:


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:

  • Equivalent function to C's "_getch()" in Java?
  • http://www.overclockers.com/forums/showthread.php?t=471633

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




回答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?




回答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



来源:https://stackoverflow.com/questions/17759142/is-there-any-equivalent-of-getch-from-c-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!