Reading a single char in Java

后端 未结 8 811
暗喜
暗喜 2020-12-01 18:17

How can a char be entered in Java from keyboard?

8条回答
  •  青春惊慌失措
    2020-12-01 18:41

    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

提交回复
热议问题