Thirteen Years of Service
Posts: 909
Threads: 43
char input 07-17-2014, 02:42 PM
#1
is there a way to take a char input from the keyboard ?
i know i can use a string input and get the first char !! but should be a way so the user can only input a char ?
•
Twelve Years of Service
Posts: 220
Threads: 6
RE: char input 07-17-2014, 03:46 PM
#2
Kinda, if you're operating in the terminal using STDIN then it is only actually considered input after the newline has been entered. You can read it char by char but you won't get the char until after the enter key has been hit. This is because the tty driver buffers the input until a newline.
There are two ways around this, accessing the event loop and hooking the keypress(or down/up) event for the window, or in C I'd use the curses library cbreak() which disables the tty buffering. A quick google shows that Java Curses implements cbreak() so that might be of use to you.
•
Twelve Years of Service
Posts: 220
Threads: 6
RE: char input 07-17-2014, 07:46 PM
#6
well cbreak would let you read the buffer as its typed so you could move on with the program after they've typed the one character without waiting on a new line.
If you want to limit what they can possible type and not just make them reenter it after they've entered too many characters then you'll need to get access to the windows event loop and capture key strokes yourself and prevent the keystroke from propagating through the handlers after they've entered one character.
Is there a reason you can't just let them enter multiple characters and only accept the first one? Or just loop until they enter valid information. That is a far more common technique than actually trying to block input.
•
Thirteen Years of Service
Posts: 909
Threads: 43
RE: char input 07-17-2014, 10:54 PM
#7
well then i guess the best to do is using charat(0) to take the first char !!
•
Fourteen Years of Service
Posts: 969
Threads: 142
RE: char input 07-19-2014, 04:25 AM
#8
Unless you are looking for command line specific solution, you could try using a KeyListener interface and adding a KeyListener using addKeyListener(Component) method.
•