Java Scanner Taking a Character Input – 接受字符输入的Java扫描器

最后修改: 2022年 9月 25日

1. Overview


In this tutorial, we’ll see how to take character input from the Scanner class.


2. Scan a Character


Java Scanner doesn’t provide any method for taking character input similar to nextInt(), nextLine(), etc.

Java Scanner没有提供任何类似nextInt()nextLine()等方法来获取字符输入。

There are a few ways we can take character input using Scanner.


Let’s first create an input string:


String input = new StringBuilder().append("abc\n")

3. Using next()


Let’s see how we can use the next() method of Scanner, and the charAt() method of String class to take a character as input:


public void givenInputSource_whenScanCharUsingNext_thenOneCharIsRead() {
    Scanner sc = new Scanner(input);
    char c =;
    assertEquals('a', c);

The next() method of Java Scanner returns a String object. We are using the charAt() method of the String class here to fetch the character from the string object.


4. Using findInLine()


This method takes a string pattern as input, and we’ll pass “.” (dot) to match only a single character. However, this will return a single character as a string, so we’ll use charAt() method to get the character:


public void givenInputSource_whenScanCharUsingFindInLine_thenOneCharIsRead() {
    Scanner sc = new Scanner(input);
    char c = sc.findInLine(".").charAt(0);
    assertEquals('a', c);

5. Using useDelimeter()


This method also scans only one character but as an object of string similar to findInLine() API. We can similarly use the charAt() method to get the character value:

这个方法也只扫描一个字符,但作为一个字符串对象,类似于findInLine() API。我们同样可以使用charAt()方法来获取字符值。

public void givenInputSource_whenScanCharUsingUseDelimiter_thenOneCharIsRead() {
    Scanner sc = new Scanner(input);
    char c = sc.useDelimiter("").next().charAt(0);
    assertEquals('a', c);

6. Conclusion


In this tutorial, we’ve learned how to take char input using the Java Scanner.

在本教程中,我们已经学会了如何使用Java Scanner获取char输入。

As always, the complete source code for the examples is available over on GitHub.