(Java) How to get user input without pressing the “enter” key [duplicate]

心不动则不痛 提交于 2021-02-05 08:46:06

问题


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.

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.

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).

Thanks in advance!


回答1:


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.

This code:

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

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

stty raw -echo

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



回答2:


You can do something like this:

import java.io.IOException;

public class MainClass {

public static void main(String[] args) {
    int inChar;
    System.out.println("Enter a Character:");
    try {
        inChar = System.in.read();
        System.out.print("You entered ");
        System.out.println(inChar);
    }
    catch (IOException e){
        System.out.println("Error reading from user");
    }
  }
}

so the command

System.in.read()

will read the char that the user have been entered.



来源:https://stackoverflow.com/questions/59742483/java-how-to-get-user-input-without-pressing-the-enter-key

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