(Java) How to get user input without pressing the "enter" key [duplicate]
Asked Answered
K

1

8

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!

Kimes answered 14/1, 2020 at 22:9 Comment(2)
From the command line? Java doesn't really support this. You can look at third party libraries, maybe something which binds into Curses for example, but remember, this is typically binding to external binaries through JNI, so it becomes complicatedLiberate
Does this answer your question? How to read a single char from the console in Java (as the user types it)?Copepod
B
-6

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.

Bloomsbury answered 14/1, 2020 at 22:59 Comment(1)
Nothing will happen until after the enter key is pressed. The OP wants to read as soon as a key is pressed.Trachoma

© 2022 - 2024 — McMap. All rights reserved.