Take a char input from the Scanner
To capture the first character of user input in Java, leverage the next().charAt(0)
method of the Scanner
class:
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
:
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:
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:
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:
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:
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:
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!
Was this article helpful?