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
AJ Longstreet
Treehouse Project ReviewerNullPointerException
Hey Guys, I'm not sure why I can't this the prompter working. I'm hoping you fine folks have some insight for me.
console.readLine() throws a NullPointerException.
package project1;
import java.io.Console;
import java.io.IOException;
class Prompter {
private static Console console = System.console();
private static String mPrompt;
static String prompt(String arg) throws IOException {
System.out.println(arg);
mPrompt = console.readLine();
return mPrompt;
}
}
3 Answers
Craig Garner
25,732 PointsIf you are running from an IDE, you may not have a console. Look at Scanner instead.
AJ Longstreet
Treehouse Project ReviewerThanks, I will look into that. I'm using IntelliJ.
Craig Garner
25,732 Pointsadded code example
David Remington
18,326 PointsIt's hard to tell without a little more context, but it looks like you want to prompt the user and then wait and read their input on the command line.
If that's the case, you'll need to use
System.out.print(arg);
instead of
System.out.println(arg);
The println method moves the cursor to the next line which will cause your console.readLine() to fire immediately instead of waiting. This could cause a NullPointerException.
David Remington
18,326 PointsThis should also work in IntelliJ's console. I ran into it a lot when I was refactoring the KarokeMachine in the IDE course.
Craig Garner
25,732 PointsCraig Garner
25,732 PointsThis is from StackOverflow
You can always use System.in and System.out instead, as follows: