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:
If you just need a single line you don't even need to go through the reader object:
sc.next().charat(0).........is the method of entering character by user based on the number entered at the run time
example: sc.next().charat(2)------------>>>>>>>>
The above code line creates cons as a null reference. The code and output are given below:
Output :
The code was tested on macbook pro with java version "1.6.0_37"
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:
And you could use it to fetch each character in your scanner like this:
The findInLine() method searches through your scanner and returns the first String that matches the regular expression you give it.
To get a
char
from aScanner
, you can use thefindInLine
method.If you need a bunch of
char
from aScanner
, then it may be more convenient to (perhaps temporarily) change the delimiter to the empty string. This will makenext()
returns a length-1 string every time.