Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

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.

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")
  .append("mno\n")
  .append("xyz\n")
  .toString();

3. Using next()

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

@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 use 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:

@Test
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 the findInLine() API. We can similarly use the charAt() method to get the character value:

@Test
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.

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

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.