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
Jonathan Grieve
Treehouse Moderator 91,254 PointsNullPointerException in Java file
Here's my file in IntelliJ IDE. I'm trying to do the simple Introductions.java project but it won't compile.
import java.io.Console;
public class Main {
public static void main(String[] args) {
Console console = System.console();
// print text to console using console object.
console.printf("Hello world");
}
}
Now I know I was originally supposed to do this file in Workspaces but I'm trying to get comfortable using the IDE. I've imported the class suggested by the IDE but I keep getting this.
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:9)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Help! :)
1 Answer
andren
28,558 PointsThe problem is that the console class does not work in most Java IDE's due to the way they run your program, this stackoverflow post provides a more detailed explanation as to why it does not work if you are curious.
This means that you have to use alternative ways to print and get input when working in your IDE.
To print you can use this command:
System.out.println("Text you want to be printed to console");
And to get input you can use this code:
Scanner scanner = new Scanner(System.in); // Write this in your code once
String input = scanner.nextLine(); // Then use scanner.nextLine as a substitute for console.readLine
Jonathan Grieve
Treehouse Moderator 91,254 PointsJonathan Grieve
Treehouse Moderator 91,254 PointsCool, thanks I'll try this out. I did try println() as an alternative but this didn't seem to work either. :-)
andren
28,558 Pointsandren
28,558 PointsMake sure you are typing System.out.println, and not console.println, the System version should work fine in intellij.
Jonathan Grieve
Treehouse Moderator 91,254 PointsJonathan Grieve
Treehouse Moderator 91,254 PointsThanks for your help, sorted. :)