Skip to content
Advertisement

How to perform unbuffered input in Java (if at all possible)?

Java Beginner here. When we input a string, we have to press the enter key to let the program know that the user has done inputting.

Is there a way where we use another key instead of enter key (for example a question mark key) to input a string?

Advertisement

Answer

Ever heard of something called a “buffer”? It is a temporary memory space where your input is stored while you enter it. As soon as you press enter, the buffer is released and the data is sent to the program. This is called “Buffered Input”. To enter stuff without pressing enter, you have to omit the scene with the buffer or, precisely, perform an “Unbuffered input”.

See this SO post: Buffered and Unbuffered Streams in Java to know about unbuffered streams provided by java. Note that they can be called “unbuffered streams” only colloquially. This is because you still have to press the enter key (yes the enter key only) to pass the input to the program. However, you can use the read() function of the InputStreamReader class to only end your input’s scope with a ? (i.e. after pressing enter, only the characters till before a ? will be read).

In C/C++, there are library functions (such as getch() in the conio.h header file recognized by Microsoft’s compilers) that allow unbuffered input/output directly. However in java, that’s not the case. If you are writing a simple console I/O program, I don’t know of any methods to help you do an unbuffered input in such a case. However if you are making GUI programs, you can make use of event handling to detect the press of a key on the keyboard and use that value in your program directly, thus inputting data without having to press enter (in fact, the enter key itself will be recognized as a separate key pressed and will return a value you could work with).

For example, you can implement KeyListener interface and in the keyPressed() method, you can use the getkeyCode() or getkeyChar() functions to determine the value of the key that was pressed and use that. For a clear illustration of this, see this SO post: Why doesn't the String object display that gets pressed key characters appended to it?.

If you want to end the input when the ? key is pressed (you mean the / key), you can just take the key presses into account before the ? press.

Hope this helps.


See for reference:

InputStreamReader javadoc: java.io.InputStreamReader.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement