Explain Codes LogoExplain Codes Logo

Take a char input from the Scanner

java
scanner
input
character
Alex KataevbyAlex Kataev·Mar 8, 2025
⚡TLDR

To capture the first character of user input in Java, leverage the next().charAt(0) method of the Scanner class:

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

In this example, the method reads the first character of the input.

Approach differences

Reading the first char

Let's start with the most popular approach, capturing the first character from a Scanner:

char firstChar = scanner.next().charAt(0);

In this case, we get the first character and the trailing characters remain in the Scanner.

Consuming single chars

To consume each character as a separate token, set the delimiter to an empty string:

scanner.useDelimiter(""); // "Pac-Man Mode" - munches tokens one char at a time char singleChar = scanner.next().charAt(0);

Now, the Scanner munches one character at a time, like Pac-Man!

Ignoring whitespace

In the case of unwanted leading whitespace, use trim to clean up:

char firstCharIgnoreSpace = scanner.next().trim().charAt(0); // Hasta la vista, space!

The above method ensures that the Scanner captures the first non-whitespace character.

Direct read method

Alternatively, you can bypass the Scanner class and read the character directly (!) from the System input:

int readChar = System.in.read(); // "goes straight for the source" char c = (char) readChar;

Remember, System.in.read() does not automatically clear the buffer after reading a character.

Code snippets & considerations

findInLine: precision over greed

To control consumption of characters, you have the findInLine method:

char preciseChar = scanner.findInLine(".").charAt(0); // less greedy, more precise

This will find the next occurrence of any character in the line and won't just consume the next token.

InputStreamReader: Bye, buffering

For buffer-proof, low-level input access, consider using the Reader API:

Reader reader = new InputStreamReader(System.in); int readCharacter = reader.read(); // the raw deal char inputChar = (char) readCharacter;

This method reads a single character without all the buffering fuss that comes with the Scanner.

Extra care for edge cases

  • Consider scenarios with internationalization, they include non-ASCII characters. A programme that respects character encoding is always poised to integrate.
  • When it comes to concurrent access to System.in, synchronise to avoid a mess.
  • Add exception handling. Practice safe coding, use protection!