Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanner method to get a char

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

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

like image 938
bizarrechaos Avatar asked Apr 08 '10 05:04

bizarrechaos


People also ask

Can Scanner read a string?

Scanner is a class in java. util package used for obtaining the input of the primitive types like int, double, etc. and strings. It is the easiest way to read input in a Java program, though not very efficient if you want an input method for scenarios where time is a constraint like in competitive programming.


2 Answers

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"
like image 154
polygenelubricants Avatar answered Sep 21 '22 18:09

polygenelubricants


You can use the Console API (which made its appearance in Java 6) as follows:

Console cons = System.console();
if(cons != null) {
  char c = (char) cons.reader().read();  // Checking for EOF omitted
  ...
}

If you just need a single line you don't even need to go through the reader object:

String s = cons.readLine();
like image 36
Itay Maman Avatar answered Sep 20 '22 18:09

Itay Maman