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

最后修改: 2022年 9月 25日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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

在本教程中,我们将看到如何从Scanner类中获取字符输入。

2. Scan a Character

2.扫描一个字符

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.

我们有几种方法可以使用Scanner来获取字符输入。

Let’s first create an input string:

让我们首先创建一个输入字符串。

String input = new StringBuilder().append("abc\n")
  .append("mno\n")
  .append("xyz\n")
  .toString();

3. Using next()

3.使用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:

让我们看看我们如何使用Scannernext()方法,以及String类的charAt()方法来获取一个字符作为输入

@Test
public void givenInputSource_whenScanCharUsingNext_thenOneCharIsRead() {
    Scanner sc = new Scanner(input);
    char c = sc.next().charAt(0);
    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.

Java扫描器的next()方法返回一个字符串对象。我们在这里使用String类的charAt()方法来从字符串对象中获取字符。

4. Using findInLine()

4.使用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:

这个方法接受一个字符串模式作为输入,我们将传递”.”(点),以只匹配一个字符。然而,这将返回一个单一字符的字符串,所以我们将使用charAt()方法来获得该字符。

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

5. Using useDelimeter()

5.使用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()方法来获取字符值。

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

6. Conclusion

6.结语

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.

一如既往,这些示例的完整源代码可在GitHub上获得over