What is the Scanner
method to get a char
returned by the keyboard in Java.
like nextLine()
for String
, nextInt()
for int
, etc.
What is the Scanner
method to get a char
returned by the keyboard in Java.
like nextLine()
for String
, nextInt()
for int
, etc.
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();
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"
Java's Scanner class does not have a built in method to read from a Scanner character-by-character.
http://java.sun.com/javase/6/docs/api/java/util/Scanner.html
However, it should still be possible to fetch individual characters from the Scanner as follows:
Scanner sc:
char c = sc.findInLine(".").charAt(0);
And you could use it to fetch each character in your scanner like this:
while(sc.hasNext()){
char c = sc.findInLine(".").charAt(0);
System.out.println(c); //to print out every char in the scanner
}
The findInLine() method searches through your scanner and returns the first String that matches the regular expression you give it.