0

Is there anyway to create a menu in Java without using a scanner class? So as soon as the press a letter or number it would run the code without pressing enter.

Voli
  • 21
  • 1
  • If you're running the application via the terminal, how *else* would you go about doing this? – Makoto Mar 01 '16 at 17:23
  • Yes, there is a way, but it is awful and involves coding in C/C++ with a JNI wrapper and compiling for a specific architecture making sure to manage your own memory. It would probably be more fun to cut off your left foot... – callyalater Mar 01 '16 at 17:25
  • 1
    Use an InputStreamReader and read every single byte of input directly. That eliminates the need for a Scanner. – f1sh Mar 01 '16 at 17:26
  • @callyalater why? What is so complicated about reading input from ``System.in`` that you need C++ for? – f1sh Mar 01 '16 at 17:27
  • @f1sh If you want to completely eliminate all Scanners, StreamReaders, dependencies on System.in, &c..., how would you get access to the hardware to get input? Also, InputStreamReaders still require the user to press enter, though `System.in.read()` would work. (I understood the question very differently.) – callyalater Mar 01 '16 at 17:28
  • [This question](http://stackoverflow.com/questions/1066318/how-to-read-a-single-char-from-the-console-in-java-as-the-user-types-it) addresses this concern as well. – callyalater Mar 01 '16 at 17:35

2 Answers2

1

No, this is not possible, at least until Java 8. In the standard JDK API there is an implicit buffer that will only be available to your program when the user presses ENTER (or some pipe or file redirect does something equivalent).

There are some libraries that sort of fix this issue but for the best of my knowledge they all need to use JNI internally. Two examples:

I have used JLine in the past with success.

Akira
  • 4,001
  • 1
  • 16
  • 24
0

In principle:

public class PressAKey {
    public static void main(String[] args) throws IOException {
        int x = System.in.read();
        System.out.println("You pressed " + (char) x);
    }
}

In practice, this doesn't work - as @Akira points out, there is a buffer that doesn't flush until enter is pressed.

slim
  • 40,215
  • 13
  • 94
  • 127