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

2018-12-31 09:54发布

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 System.console?

Console co=System.console();
System.out.println(co);
try{
    String s=co.readLine();
}

标签: java
9条回答
弹指情弦暗扣
2楼-- · 2018-12-31 10:05

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.
查看更多
忆尘夕之涩
3楼-- · 2018-12-31 10:06

Using Console to read input(usable only outside IDE):

System.out.print("Enter something:");
String input = System.console().readLine();

Another way(works everywhere):

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {
    public static void main(String[] args) throws IOException { 
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter String");
        String s = br.readLine();
        System.out.print("Enter Integer:");
        try{
            int i = Integer.parseInt(br.readLine());
        }catch(NumberFormatException nfe){
            System.err.println("Invalid Format!");
        }
    }
}

System.console() returns null in an IDE
so if you really need to use System.console(), read this solution from McDowell.

查看更多
只靠听说
4楼-- · 2018-12-31 10:07
Scanner in = new Scanner(System.in);

int i = in.nextInt();
String s = in.next();
查看更多
浅入江南
6楼-- · 2018-12-31 10:23

I wrote the Text-IO library, which can deal with the problem of System.console() being null when running an application from within an IDE.

It introduces an abstraction layer similar to the one proposed by McDowell. If System.console() returns null, the library switches to a Swing-based console.

In addition, Text-IO has a series of useful features:

  • supports reading values with various data types.
  • allows masking the input when reading sensitive data.
  • allows selecting a value from a list.
  • allows specifying constraints on the input values (format patterns, value ranges, length constraints etc.).

Usage example:

TextIO textIO = TextIoFactory.getTextIO();

String user = textIO.newStringInputReader()
        .withDefaultValue("admin")
        .read("Username");

String password = textIO.newStringInputReader()
        .withMinLength(6)
        .withInputMasking(true)
        .read("Password");

int age = textIO.newIntInputReader()
        .withMinVal(13)
        .read("Age");

Month month = textIO.newEnumInputReader(Month.class)
        .read("What month were you born in?");

textIO.getTextTerminal().println("User " + user + " is " + age + " years old, " +
        "was born in " + month + " and has the password " + password + ".");

In this image you can see the above code running in a Swing-based console.

查看更多
查无此人
7楼-- · 2018-12-31 10:24

Try this. hope this will help.

    String cls0;
    String cls1;

    Scanner in = new Scanner(System.in);  
    System.out.println("Enter a string");  
    cls0 = in.nextLine();  

    System.out.println("Enter a string");  
    cls1 = in.nextLine(); 
查看更多
登录 后发表回答