Take a char input from the Scanner

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

    You should get the String using scanner.next() and invoke String.charAt(0) method on the returned String.
    Exmple :

        import java.util.Scanner;
    
        public class InputC{
    
    
                public static void main(String[] args) {
                    // TODO Auto-generated method stub
                       // Declare the object and initialize with
                       // predefined standard input object
                        Scanner scanner = new Scanner(System.in);
                        System.out.println("Enter a character: ");
                        // Character input
                        char c = scanner.next().charAt(0);
                        // Print the read value
                        System.out.println("You have entered: "+c);
                }
    
    
            }
    

    output

    Enter a character: 
    a
    You have entered: a
    

提交回复
热议问题