2

i am using the following simple code to read a line of string from console but get nullpointerexception, can you folks help:

import java.io.Console;

public class readline_String {

    public static void main(String[] args)
    {
        // TODO Auto-generated method stub

        //String str=System.console().readLine();
        System.out.println("Enter an input string:");
        Console c=System.console();
        String str=c.readLine();
        System.out.println("The input string is:");
        System.out.println(str);

    }

}
YCF_L
  • 51,266
  • 13
  • 85
  • 129
Dilip Jena
  • 21
  • 2
  • 4
    From the doc of `System.console()` : "Returns : The system console, if any, otherwise _null_." – Arnaud Mar 06 '18 at 10:40
  • read this https://stackoverflow.com/questions/4644415/java-how-to-get-input-from-system-console – YCF_L Mar 06 '18 at 10:41
  • Follow Java Naming Conventions: class names should start with uppercase. And don't use underscores, except for constants. – MC Emperor Mar 06 '18 at 10:45

2 Answers2

2

Replace your code with:

    System.out.println("Enter an input string:");
    Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();
    System.out.println("The input string is:");
    System.out.println(str);
Maciej
  • 1,874
  • 9
  • 14
2

If you are trying in a IDE(ex: NetBeans) it might show NullPointerException

It shows proper output in a cmd: code:

public class InputConsole {
    public static void main(String[] args) {
        System.out.print("Enter something:");
String input = System.console().readLine();
        System.out.println("input: "+input);
    }
}

Output:

enter image description here

Alternatively you can use Scanner or BufferedReader

Mamun Kayum
  • 176
  • 7