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);

    }

}
3
  • 4
    From the doc of System.console() : "Returns : The system console, if any, otherwise null." Commented Mar 6, 2018 at 10:40
  • read this stackoverflow.com/questions/4644415/… Commented Mar 6, 2018 at 10:41
  • Follow Java Naming Conventions: class names should start with uppercase. And don't use underscores, except for constants. Commented Mar 6, 2018 at 10:45

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Maciej, thanks so much this works. Not sure why it doesn't work with system.console.readline()
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.