How can I read input from the console using the Scanner class in Java?

前端 未结 15 2399
我寻月下人不归
我寻月下人不归 2020-11-21 06:19

How could I read input from the console using the Scanner class? Something like this:

System.out.println(\"Enter your username: \");
Scanner = i         


        
15条回答
  •  甜味超标
    2020-11-21 06:50

    There is a simple way to read from the console.

    Please find the below code:

    import java.util.Scanner;
    
        public class ScannerDemo {
    
            public static void main(String[] args) {
                Scanner sc = new Scanner(System.in);
    
                // Reading of Integer
                int number = sc.nextInt();
    
                // Reading of String
                String str = sc.next();
            }
        }
    

    For a detailed understanding, please refer to the below documents.

    Doc

    Now let's talk about the detailed understanding of the Scanner class working:

    public Scanner(InputStream source) {
        this(new InputStreamReader(source), WHITESPACE_PATTERN);
    }
    

    This is the constructor for creating the Scanner instance.

    Here we are passing the InputStream reference which is nothing but a System.In. Here it opens the InputStream Pipe for console input.

    public InputStreamReader(InputStream in) {
        super(in);
        try {
            sd = StreamDecoder.forInputStreamReader(in, this, (String)null); // ## Check lock object
        }
        catch (UnsupportedEncodingException e) {
            // The default encoding should always be available
            throw new Error(e);
        }
    }
    

    By passing the System.in this code will opens the socket for reading from console.

提交回复
热议问题