Take a char input from the Scanner

前端 未结 22 2247
[愿得一人]
[愿得一人] 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:57

    There is no API method to get a character from the Scanner. You should get the String using scanner.next() and invoke String.charAt(0) method on the returned String.

    Scanner reader = new Scanner(System.in);
    char c = reader.next().charAt(0);
    

    Just to be safe with whitespaces you could also first call trim() on the string to remove any whitespaces.

    Scanner reader = new Scanner(System.in);
    char c = reader.next().trim().charAt(0);
    

提交回复
热议问题