You could take the first character from Scanner.next
:
char c = reader.next().charAt(0);
To consume exactly one character you could use:
char c = reader.findInLine(".").charAt(0);
To consume strictly one character you could use:
char c = reader.next(".").charAt(0);
Setup scanner:
reader.useDelimiter("");
After this reader.next()
will return a single-character string.
There is no API method to get a character from the Scanner. You should get the String using scanner.next()
and invoke String.charAt(0)
method on the returned String.
Scanner reader = new Scanner(System.in);
char c = reader.next().charAt(0);
Just to be safe with whitespaces you could also first call trim()
on the string to remove any whitespaces.
Scanner reader = new Scanner(System.in);
char c = reader.next().trim().charAt(0);
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 cause next()
to tokenize into strings that are exactly one character long. So then you can repeatedly call next().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:
Reader reader = new InputStreamReader(System.in);
int ch = reader.read();
if (ch != -1) { // check for EOF
// we have a character ...
}
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:
You can solve this problem, of "grabbing keyboard input one char at a time" very simply. Without having to use a Scanner all and also not clearing the input buffer as a side effect, by using this.
char c = (char)System.in.read();
If all you need is the same functionality as the C language "getChar()" function then this will work great. The Big advantage of the "System.in.read()" is the buffer is not cleared out after each char your grab. So if you still need all the users input you can still get the rest of it from the input buffer. The "char c = scanner.next().charAt(0);"
way does grab the char but will clear the buffer.
// Java program to read character without using Scanner
public class Main
{
public static void main(String[] args)
{
try {
String input = "";
// Grab the First char, also wait for user input if the buffer is empty.
// Think of it as working just like getChar() does in C.
char c = (char)System.in.read();
while(c != '\n') {
//<do your magic you need to do with the char here>
input += c; // <my simple magic>
//then grab the next char
c = (char)System.in.read();
}
//print back out all the users input
System.out.println(input);
} catch (Exception e){
System.out.println(e);
}
}
}
Hope this helpful, and good luck! P.S. Sorry i know this is an older post, but i hope that my answer bring new insight and could might help other people who also have this problem.
This actually doesn't work:
char c = reader.next().charAt(0);
There are some good explanations and references in this question: Why doesn't the Scanner class have a nextChar method? "A Scanner breaks its input into tokens using a delimiter pattern", which is pretty open ended. For example when using this
c = lineScanner.next().charAt(0);
for this line of input "(1 + 9) / (3 - 1) + 6 - 2" the call to next returns "(1", c will be set to '(', and you'll end up losing the '1' on the next call to next()
Typically when you want to get a character you would like to ignore whitespace. This worked for me:
c = lineScanner.findInLine("[^\\s]").charAt(0);
Reference: regex to match a single character that is anything but a space
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With