Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Basics Getting Started with Java Receiving Input

Annuradha Raychaudhury
Annuradha Raychaudhury
9,433 Points

readLine() not working on eclipse luna with java version "1.8.0_45"

import java.io.Console;

public class Input_Output {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Console console = System.console();
    //String firstName = "Ben";
    String firstName = console.readLine("What is your Name?  ");

    console.printf("Hello my name is %s\n", firstName);


}

}

error:Exception in thread "main" java.lang.NullPointerException at Input_Output.main(Input_Output.java:10)

Jonas Schindler
Jonas Schindler
4,085 Points

Is the code not running at all? Or where exactly does it crash?

2 Answers

Daniel Babbev
Daniel Babbev
10,354 Points

The Console class does not work as you expect in IDEs. Instead you should use java.util.Scanner or java.io.BufferedReader. I recommend that you use the Scanner class, because BufferedReader throws an IOException. Here is an example:

import java.util.Scanner;
 //main method here
Scanner scanIn = new Scanner(System.in);
String myString = scanIn.nextLine();
int myNumber = scanIn.nextInt();
//notice that I use "nextLine()" for strings and "nextInt()" for integers!

You can read more about the Scanner class in the javadoc here

Annuradha Raychaudhury
Annuradha Raychaudhury
9,433 Points

Thanks it worked with Scanner, Also for showing how to initialize and use scanner.

Kirubel Tesfaye
Kirubel Tesfaye
814 Points

if it does not work on IDEs then what does it work on?

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Some IDEs will return NPE for Console class. System.console() returns null if there is no console. You can use the Scanner class and do it easily:

try this:

      Scanner scan = new Scanner(System.in);
      System.out.println("Enter a Name:");
      String s = scan.next();
Annuradha Raychaudhury
Annuradha Raychaudhury
9,433 Points

Thank you for the Scanner suggestion, It works. Just that scan.next(); does not work instead i tried scanIn.next(); Another thing that helped was location of println in the code. Great help