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

后端 未结 9 1889
时光说笑
时光说笑 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条回答
  •  面向向阳花
    2020-11-22 09:48

    There are few ways to read input string from your console/keyboard. The following sample code shows how to read a string from the console/keyboard by using Java.

    public class ConsoleReadingDemo {
    
    public static void main(String[] args) {
    
        // ====
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Please enter user name : ");
        String username = null;
        try {
            username = reader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("You entered : " + username);
    
        // ===== In Java 5, Java.util,Scanner is used for this purpose.
        Scanner in = new Scanner(System.in);
        System.out.print("Please enter user name : ");
        username = in.nextLine();      
        System.out.println("You entered : " + username);
    
    
        // ====== Java 6
        Console console = System.console();
        username = console.readLine("Please enter user name : ");   
        System.out.println("You entered : " + username);
    
    }
    }
    

    The last part of code used java.io.Console class. you can not get Console instance from System.console() when running the demo code through Eclipse. Because eclipse runs your application as a background process and not as a top-level process with a system console.

提交回复
热议问题