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

后端 未结 9 1700
时光说笑
时光说笑 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:54

    Using Console to read input (usable only outside of an 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.

提交回复
热议问题