How can a char be entered in Java from keyboard?
You can use Scanner like so:
Scanner s= new Scanner(System.in);
char x = s.next().charAt(0);
By using the charAt function you are able to get the value of the first char without using external casting.
Here is a class 'getJ' with a static function 'chr()'. This function reads one char.
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
class getJ {
static char chr()throws IOException{
BufferedReader bufferReader =new BufferedReader(new InputStreamReader(System.in));
return bufferReader.readLine().charAt(0);
}
}
In order to read a char use this:
anyFunc()throws IOException{
...
...
char c=getJ.chr();
}
Because of 'chr()' is static, you don't have to create 'getJ' by 'new' ; I mean you don't need to do:
getJ ob = new getJ;
c=ob.chr();
You should remember to add 'throws IOException' to the function's head. If it's impossible, use try / catch as follows:
anyFunc(){// if it's impossible to add 'throws IOException' here
...
try
{
char c=getJ.chr(); //reads a char into c
}
catch(IOException e)
{
System.out.println("IOException has been caught");
}
Credit to: tutorialspoint.com
See also: geeksforgeeks.
java bufferedreader input getchar char