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

Daniel Kirwan
Daniel Kirwan
1,094 Points

Why doesn't the code from the workspace, run in Bluej or Eclipse compiler?

This is the code

import java.io.Console;

public class Introductions {

    public static void main(String[] args) {
        Console console = System.console();
        // Welcome to the Introductions program!  Your code goes below here
      String firstName = console.readLine("what is your name? ");
      // thisIsAnExampleOfCamelCasing
        console.printf("Hello my name is %s\n", firstName);
        console.printf("%s is learning to write Java\n", firstName);

  }
}

This is the error received java.lang.NullPointerException on the line

String firstName = console.readLine("What is your name? ");

1 Answer

Stone Preston
Stone Preston
42,016 Points

the Console only works when using the command line interface to compile and run.

If you are using an IDE, you need to use System.out.print to print strings, System.out.printf to print formatted strings, and the nextLine method of the Scanner class to read in user input. In order to use the Scanner class you need to import it and create a new Scanner object. you can then reference that object and call the nextLine method to get user input

import java.util.Scanner;

public class Introductions {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // Welcome to the Introductions program!  Your code goes below here
      System.out.print("what is your name: ");
      String firstName = scan.nextLine();
      // thisIsAnExampleOfCamelCasing
        System.out.printf("Hello my name is %s\n", firstName);
        System.out.printf("%s is learning to write Java\n", firstName);

  }
}
Daniel Kirwan
Daniel Kirwan
1,094 Points

Thanks. That has helped a lot.

Marta Dias
Marta Dias
9,240 Points

thanks a million. I was struggling with my code too.