(Java) 如何在不按“输入"的情况下获取用户输入?钥匙

2022-01-19 00:00:00 input switch-statement java instant

我很好奇,想在 java 中测试这种类型的东西.我在网上查了一下,并没有真正找到任何对我发现的任何问题有帮助的东西;所以我决定自己问.

I was curious and wanted to test this type of thing out in java. I looked it up online and couldn't really find anything that helped out in any of the questions I found; so I decided to ask it myself.

在我写出的示例中,您获得了几个选项,并且您获得了用户输入,然后使用 switch 语句根据用户输入发生事情.发生什么并不重要,因为我试图弄清楚如何在无需按 Enter 的情况下获取用户输入.

In the example I wrote out, you're given a couple of options and you get user input and then stuff happens based off of user input using a switch statement. Doesn't really matter what happens as I'm trying to figure out how to get user input without having to press enter.

因此,例如,如果用户必须在 1、2、3、4 或 5 之间选择输入,例如,当用户按下2"时,程序会立即读取此输入,而无需他们按下进入.有没有办法做到这一点?我也在 Windows 10 上使用 cmd (虽然我在 NetBeans 上做项目时考虑过,但我认为这不会有什么不同).

So, for example, if the user has to choose between 1, 2, 3, 4, or 5 for input, when the user presses '2', for example, the program reads this input instantly without them having to press enter. Is there any way to do this? I'm using cmd on Windows 10 as well (thought about it when I was doing a project on NetBeans though, this shouldn't make a difference I don't think).

提前致谢!

推荐答案

您需要以某种方式运行您的程序,而不是对用户输入进行行缓冲.

You need to run your program in some way that doesn't line-buffer user input.

很多细节这里和一些相关的讨论 这里.

Lots of detail here and some related discussion here.

这段代码:

public static void main(String[] args) throws IOException {
    System.out.print("hit a key: ");
    System.out.print(System.in.read());
}

和 OS X 上的终端"应用程序:

and a "Terminal" app on OS X with this:

stty raw -echo

运行时的行为是这样的(上面的代码在一个名为 Scratch.java 的文件中,我输入了一个 A 作为输入):

behaves like this when run (where the above code is in a file named Scratch.java, and I typed a single A as input):

$ stty raw && java Scratch
hit a key: 65

相关文章