How to scan (accept) a single character in Java?9 months ago

There is NO method as nextChar() in java.util.Scanner class in Java. We need to use the next() method to read a single character as a string and then use charAt(0) to get the first character of that string.

Scanner scanner = new Scanner(System.in);
String str = scanner.next();
char ch = str.charAt(0);

or

Scanner scanner = new Scanner(System.in);
char ch = scanner.next().charAt(0);

The below program accepts a character and prints the same character as the output.

import java.util.*;

public class Hello {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        char ch = scanner.next().charAt(0);
        System.out.println(ch);
    }

}

Note: Here we are reading the single character as a string and getting the first character using charAt(0) from that string.