What is the Scanner
method to get a char
returned by the keyboard in Java.
like nextLine()
for String
, nextInt()
for int
, etc.
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.
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"
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With