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 trialEzekiel dela Peña
6,231 PointsHow to fix java.lang.NullPointerException?
I'm currently using Eclipse LUNA (JAVA EE IDE) and I'm currently doing the prompting guess activity on a Java Basic Course.
ERROR MESSAGE: Exception in thread "main" java.lang.NullPointerException at projectHangMan.Prompter.promptForGuess(Prompter.java:13) at projectHangMan.Hangman.main(Hangman.java:10)
The error is pointing me to this code: String guessAsString = console.readLine("Enter a letter: ");
I guess, that is not working because of the console. But I don't know how to fix this problem.
Thanks in advance!
2 Answers
William Li
Courses Plus Student 26,868 PointsHi, Ezekiel dela Peña the NullPointerException you're getting here is because you're running your Java Code in an IDE (i.e. Eclipse, NetBeans), in an IDE environment, the console
object isn't available to you; hence the NullPointerException.
In order for it to work, you have to run your code in a console environment.
IF you prefer to you Eclipse to follow along with the course; I'd suggest that you use Scanner , BufferedReader , or InputStreamReader class to get user input; and something like System.out.printf()
for output.
aneaswiley
Courses Plus Student 1,612 PointsHopefully the image shows up but I am using IntelliJ and I couldn't use the Console object I tried to use the Scanner object but I am getting even more errors. Anyone come accross this because I would love to implement this and get familiar with this in a real World environment.
Thanks
Craig Dennis
Treehouse TeacherI don't see your errors, can you post them please? Don't worry we are headed straight to the IDEs soon!
Sahil Nabizada
15,696 PointsI had the same problem with in Eclipse. So I used Scanner object like this.
import java.util.Scanner;
public class Prompter { private Game mGame;
public Prompter(Game game) {
mGame = game;
}
public boolean promptForGuess() {
Scanner input = new Scanner(System.in);
System.out.println("Enter a Letter: ");
String guessAsString = input.nextLine();
char guess = guessAsString.charAt(0);
return mGame.applyGuess(guess);
}
} I hope that helps.
Craig Dennis
Treehouse TeacherCraig Dennis
Treehouse TeacherYou can do that locally by navigating in a command prompt to the directory and running java Example.
BufferedReader
has the readLine you want like so: