What is the Scanner
method to get a char
returned by the keyboard in Java.
like nextLine()
for String
, nextInt()
for int
, etc.
This question is related to
java
char
java.util.scanner
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();
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)------------>>>>>>>>
Scanner sc = new Scanner (System.in)
char c = sc.next().trim().charAt(0);
Console cons = System.console();
The above code line creates cons as a null reference. The code and output are given below:
Console cons = System.console();
if (cons != null) {
System.out.println("Enter single character: ");
char c = (char) cons.reader().read();
System.out.println(c);
}else{
System.out.println(cons);
}
Output :
null
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:
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.
Source: Stackoverflow.com