This is the code I have:
import java.io.DataInputStream;
import java.io.InputStream;
public class TestClass {
public static void main(String[] args) throws Exception {
InputStream inputStream = new DataInputStream(System.in);
int read = inputStream.read();
System.out.println(read);
}
}
When I run this code inputStream will wait for input from the standard input which is fine. When I type 'a' in keyboard, I expect 97 to be printed immediately in the console. However this code requires me to hit 'Enter' after I type 'a'.
If I simply hit 'Enter' integer 10 will be shown in the console.
How can I modify the code so that as soon as I hit 'a' in the keyboard I see the integer 97? What is so special about the Enter button in this case? Why do I need to hit Enter?
Sadly there's no way to do this with the console in Java. No matter whether you use a java.util.Scanner
or a kind of java.io.InputStream
(including System.in
directly), the Enter
key is always the trigger for input to be received.
Consider using a graphical user interface like Swing (definition on wikipedia), where you can fulfill your input requirements by hooking up a KeyListener
to a text box.