Scanner method to get a char

bizarrechaos picture bizarrechaos · Apr 8, 2010 · Viewed 119.3k times · Source

What is the Scanner method to get a char returned by the keyboard in Java.

like nextLine() for String, nextInt() for int, etc.

Answer

polygenelubricants picture polygenelubricants · Apr 8, 2010

To get a char from a Scanner, you can use the findInLine method.

    Scanner sc = new Scanner("abc");
    char ch = sc.findInLine(".").charAt(0);
    System.out.println(ch); // prints "a"
    System.out.println(sc.next()); // prints "bc"

If you need a bunch of char from a Scanner, then it may be more convenient to (perhaps temporarily) change the delimiter to the empty string. This will make next() returns a length-1 string every time.

    Scanner sc = new Scanner("abc");
    sc.useDelimiter("");
    while (sc.hasNext()) {
        System.out.println(sc.next());
    } // prints "a", "b", "c"