Reading a single char in Java

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

How can a char be entered in Java from keyboard?

相关标签:
8条回答
  • 2020-12-01 18:37

    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.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题