Java: How to get input from System.console()

后端 未结 9 1715
时光说笑
时光说笑 2020-11-22 09:08

I am trying to use Console class to get input from user but a null object is returned when I call System.console(). Do I have to change anything before using Sy

9条回答
  •  -上瘾入骨i
    2020-11-22 09:38

    The following takes athspk's answer and makes it into one that loops continually until the user types "exit". I've also written a followup answer where I've taken this code and made it testable.

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class LoopingConsoleInputExample {
    
       public static final String EXIT_COMMAND = "exit";
    
       public static void main(final String[] args) throws IOException {
          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
          System.out.println("Enter some text, or '" + EXIT_COMMAND + "' to quit");
    
          while (true) {
    
             System.out.print("> ");
             String input = br.readLine();
             System.out.println(input);
    
             if (input.length() == EXIT_COMMAND.length() && input.toLowerCase().equals(EXIT_COMMAND)) {
                System.out.println("Exiting.");
                return;
             }
    
             System.out.println("...response goes here...");
          }
       }
    }
    

    Example output:

    Enter some text, or 'exit' to quit
    > one
    one
    ...response goes here...
    > two
    two
    ...response goes here...
    > three
    three
    ...response goes here...
    > exit
    exit
    Exiting.
    

提交回复
热议问题