I am trying to find a way to take a char
input from the keyboard.
I tried using:
Scanner reader = new Scanner(System.in);
char c = reader.nextChar();
This method doesn't exist.
I tried taking c
as a String
. Yet, it would not always work in every case, since the other method I am calling from my method requires a char
as an input. Therefore I have to find a way to explicitly take a char as an input.
Any help?
There are three ways to approach this problem:
Call
next()
on the Scanner, and extract the first character of the String (e.g.charAt(0)
) If you want to read the rest of the line as characters, iterate over the remaining characters in the String. Other answers have this code.Use
setDelimiter("")
to set the delimiter to an empty string. This will causenext()
to tokenize into strings that are exactly one character long. So then you can repeatedly callnext().charAt(0)
to iterate the characters. You can then set the delimiter to its original value and resume scanning in the normal way!Use the Reader API instead of the Scanner API. The
Reader.read()
method delivers a single character read from the input stream. For example:When you read from the console via
System.in
, the input is typically buffered by the operating system, and only "released" to the application when the user types ENTER. So if you intend your application to respond to individual keyboard strokes, this is not going to work. You would need to do some OS-specific native code stuff to turn off or work around line-buffering for console at the OS level.Reference:
The best way to take input of a character in Scanner class is: