Take a char input from the Scanner

前端 未结 22 2845
[愿得一人]
[愿得一人] 2020-11-22 05:16

I am trying to find a way to take a char input from the keyboard.

I tried using:

Scanner reader = new Scanner(System.in);
char c = reade         


        
22条回答
  •  忘掉有多难
    2020-11-22 05:59

    Scanner key = new Scanner(System.in);
    //shortcut way 
    char firstChar=key.next().charAt(0);  
    //how it works;
    /*key.next() takes a String as input then,
    charAt method is applied on that input (String)
    with a parameter of type int (position) that you give to get      
    that char at that position.
    You can simply read it out as: 
    the char at position/index 0 from the input String
    (through the Scanner object key) is stored in var. firstChar (type char) */
    
    //you can also do it in a bit elabortive manner to understand how it exactly works
    String input=key.next();  // you can also write key.nextLine to take a String with spaces also
    char firstChar=input.charAt(0);
    char charAtAnyPos= input.charAt(pos);  // in pos you enter that index from where you want to get the char from
    

    By the way, you can't take a char directly as an input. As you can see above, a String is first taken then the charAt(0); is found and stored

提交回复
热议问题