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 is no API method to get a character from the Scanner. You should get the String using
scanner.next()
and invokeString.charAt(0)
method on the returned String.Just to be safe with whitespaces you could also first call
trim()
on the string to remove any whitespaces.To get only one character char c = reader.next(".").charAt(0);
This actually doesn't work:
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
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:
Reference: regex to match a single character that is anything but a space
The easiest way is, first change the variable to a String and accept the input as a string. Then you can control based on the input variable with an if-else or switch statement as follows.
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.
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.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.
You could use typecasting:
This way you will take input in String due to the function 'next()' but then it will be converted into character due to the 'char' mentioned in the brackets.
This method of conversion of data type by mentioning the destination data type in brackets is called typecating. It works for me, I hope it works for u :)