Take a char input from the Scanner

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

    There are two approaches, you can either take exactly one character or strictly one character. When you use exactly, the reader will take only the first character, irrespective of how many characters you input.

    For example:

    import java.util.Scanner;  
    
    public class ReaderExample {  
    
        public static void main(String[] args) {  
    
            try {  
    
            Scanner reader = new Scanner(System.in);
    
            char c = reader.findInLine(".").charAt(0);
    
                reader.close();  
    
                System.out.print(c);
    
            } catch (Exception ex) {  
    
                System.out.println(ex.getMessage());  
    
            }
    
    
    
        }  
    
    }  
    

    When you give a set of characters as input, say "abcd", the reader will consider only the first character i.e., the letter 'a'

    But when you use strictly, the input should be just one character. If the input is more than one character, then the reader will not take the input

    import java.util.Scanner;  
    
    public class ReaderExample {  
    
        public static void main(String[] args) {  
    
            try {  
    
            Scanner reader = new Scanner(System.in);
    
            char c = reader.next(".").charAt(0);
    
                reader.close();  
    
                System.out.print(c);
    
            } catch (Exception ex) {  
    
                System.out.println(ex.getMessage());  
    
            }
    
    
    
        }  
    
    }  
    

    Suppose you give input "abcd", no input is taken, and the variable c will have Null value.

提交回复
热议问题