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

    }

}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Dilip Jena
  • 21
  • 2

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,954
  • 10
  • 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
  • 161
  • 7