+ 1
How to read a single character in java Scanner object
There is nothing like nextChar() and if I try to use nextByte() for the purpose, it gives error. I am trying something like this. Scanner inp = new Scanner(System.in); char inputchar = inp.nextByte();
1 Answer
+ 2
The reason why you are receiving errors is because a single character is too big (16-bit) to be assigned to a byte (which has 8-bits).
Step-by-step on how to get a single character from the standard user input:
1.) Change the assignment to:
String inputchar = inp.next();
*this will store a single word in the variable
2.) If the user types a single character, your program will run as it should without errors because Strings (32-bit) are able to store a single character (16-bit)
3.) However, if the user types more than a single character, the String method charAt() and the variable that you used to store the user input will be very useful. This is how the additional line of code should look like with the example variable of "finalChar":
char finalChar = inputchar.charAt(0);
Sorry if it was a bit too long, hope this helps!