Scanner and nextChar() in Java
Scanner class in Java supports nextInt(), nextLong(), nextDouble() etc. But there is no nextChar() (See this for examples)
To read a char, we use next().charAt(0). next() function returns the next token/word in the input as a string and charAt(0) function returns the first character in that string.
// Java program to read character using Scanner // class import java.util.Scanner; public class ScannerDemo1 { public static void main(String[] args) { // Declare the object and initialize with // predefined standard input object Scanner sc = new Scanner(System.in); // Character input char c = sc.next().charAt(0); // Print the read value System.out.println("c = "+c); } } |
chevron_right
filter_none
Input :
g
Output :
c = g
This article is contributed by Piyush Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Recommended Posts:
- Java.util.BitSet class methods in Java with Examples | Set 2
- Shadowing of static functions in Java
- How does default virtual behavior differ in C++ and Java ?
- How are Java objects stored in memory?
- How are parameters passed in Java?
- Are static local variables allowed in Java?
- final variables in Java
- Default constructor in Java
- Assigning values to static final variables in Java
- Comparison of Exception Handling in C++ and Java
- Does Java support goto?
- Arrays in Java
- Inheritance and constructors in Java
- More restrictive access to a derived class method in Java
- Comparison of static keyword in C++ and Java



