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

前端 未结 15 1981
我寻月下人不归
我寻月下人不归 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 07:08

    Reading Data From The Console

    • BufferedReader is synchronized, so read operations on a BufferedReader can be safely done from multiple threads. The buffer size may be specified, or the default size(8192) may be used. The default is large enough for most purposes.

      readLine() « just reads data line by line from the stream or source. A line is considered to be terminated by any one these: \n, \r (or) \r\n

    • Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace(\s) and it is recognised by Character.isWhitespace.

      « Until the user enters data, the scanning operation may block, waiting for input. « Use Scanner(BUFFER_SIZE = 1024) if you want to parse a specific type of token from a stream. « A scanner however is not thread safe. It has to be externally synchronized.

      next() « Finds and returns the next complete token from this scanner. nextInt() « Scans the next token of the input as an int.

    Code

    String name = null;
    int number;
    
    java.io.BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    name = in.readLine(); // If the user has not entered anything, assume the default value.
    number = Integer.parseInt(in.readLine()); // It reads only String,and we need to parse it.
    System.out.println("Name " + name + "\t number " + number);
    
    java.util.Scanner sc = new Scanner(System.in).useDelimiter("\\s");
    name = sc.next();  // It will not leave until the user enters data.
    number = sc.nextInt(); // We can read specific data.
    System.out.println("Name " + name + "\t number " + number);
    
    // The Console class is not working in the IDE as expected.
    java.io.Console cnsl = System.console();
    if (cnsl != null) {
        // Read a line from the user input. The cursor blinks after the specified input.
        name = cnsl.readLine("Name: ");
        System.out.println("Name entered: " + name);
    }
    

    Inputs and outputs of Stream

    Reader Input:     Output:
    Yash 777          Line1 = Yash 777
         7            Line1 = 7
    
    Scanner Input:    Output:
    Yash 777          token1 = Yash
                      token2 = 777
    

提交回复
热议问题