javainputcharjava.util.scanner

Take a char input from the Scanner


I am trying to find a way to take a char input from the keyboard.

I tried using:

Scanner reader = new Scanner(System.in);
char c = reader.nextChar();

This method doesn't exist.

I tried taking c as a String. Yet, it would not always work in every case, since the other method I am calling from my method requires a char as an input. Therefore I have to find a way to explicitly take a char as an input.

Any help?


Solution

  • You could take the first character from Scanner.next:

    char c = reader.next().charAt(0);
    

    To consume exactly one character you could use:

    char c = reader.findInLine(".").charAt(0);
    

    To consume strictly one character you could use:

    char c = reader.next(".").charAt(0);