Taking character input in Java isn’t as simple as taking input as a string or integer. The Scanner class in Java works with nextInt(), nextLong(), nextDouble(), etc. However, it does not support nextChar in Java, which makes taking character input slightly more complicated. If you’re looking to take char input in Java and nextChar() isn’t working, here’s how you can take input as char properly.Is there nextChar() in Scanner Class in Java? - 1

nextChar() scanner class in Java

There is no classical nextChar() method in Java Scanner class. The best and most simple alternative to taking char input in Java would be the next().charAt(0). The charAt(0) command is used in combination with the simple next() command which instructs Java to record the next character or string that is input into the command line. This input can be a string, character, or numeral. The charAt command is a way to filter the unwanted data types and only restricts the input to char data type. Since charAt only returns output in the form of a char value, it converts any type of data type to a char type. To take a char input using Scanner and next(), you can use these two lines of code.
Scanner input = new Scanner (system.in);
char a = input.next().charAt(0);
When you use next(), you’re telling Java that it's about to accept an input of an unspecified data type. This input can contain an infinite amount of characters. However, by using the charAt command and passing ‘0’ as the index, you’re only taking a single character as input and storing it into a variable. The return value of the input line will be a single character. Since we instructed the compiler to accept whatever input it was going to receive next, it doesn’t care that only a single character was initialized. Coding examples to accept a char input in Java is written below.
import java.util.Scanner;
   public class CharExample {
       public static void main(String[] args) {

           //Initializing input
           Scanner input = new Scanner(System.in);
           System.out.print("Input any character: ");

           //Using next().charAt(0) to Accept Char Input
           char a = input.next().charAt(0);

           //Printing the Contents of 'a'
           System.out.println("The Variable A Contains the Following Data: " + a);
       }
   }
The output is:
Input any character: l The Variable A Contains the Following Data: l
There are other alternatives to accept char input from users in Java. You could use the reader.useDelimiter(“”) and reader.next() which is also an intuitive way to get the task done.Is there nextChar() in Scanner Class in Java? - 2