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

后端 未结 9 1702
时光说笑
时光说笑 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.

    0 讨论(0)
  • 2020-11-22 09:59

    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(); 
    
    0 讨论(0)
  • 2020-11-22 10:00

    Found some good answer here regarding reading from console, here another way use 'Scanner' to read from console:

    import java.util.Scanner;
    String data;
    
    Scanner scanInput = new Scanner(System.in);
    data= scanInput.nextLine();
    
    scanInput.close();            
    System.out.println(data);
    
    0 讨论(0)
提交回复
热议问题