+ 2

How to input char in java using scanner?

Scanner sc = new Scanner(System.in); char move = sc.next().charAt(0); // why like this char move = sc.nextChar() // why i cant define like this as integer nextInt() So explain PLease

27th Mar 2021, 2:55 AM
Sachin Saxena
Sachin Saxena - avatar
3 Answers
+ 4
First let me tell you a bit about next(). This method accepts the next token as a word/string. You cannot take a whole line of text as input from the user with this method. For example, if I were to input "Hello World!", the input would be only Hello. This is again because it takes only one word as an input string. Note that the input can also be one letter because it'll still be treated as a string. Moving on to charAt() method. This method returns a character of a string at a specified index. Like most programming languages, java also starts counting things from 0. For example, take a string myStr = "Java". The positions of the characters are respectively as follows - 'J' - 0 'a' - 1 'v' - 2 'a' - 3 So the line sc.next().charAt(0) can be broken down as follows - sc.next() accepts a string from the user. Now you use charAt(0) to get the first character of that input string as a character. Always remember that sc.next() returns a String whereas charAt() returns a char. Hope that makes sense now :)
27th Mar 2021, 3:20 AM
Soumik
Soumik - avatar
+ 3
There is not a method by the name `nextChar()` in Scanner class. It is a design policy for the language I suppose. https://tutorialspoint.dev/language/java/gfact-51-java-scanner-nextchar
27th Mar 2021, 3:18 AM
Ipang