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 trialRik-Jan van Bree
1,084 Pointsnon-static method promptForGuess() cannot be referenced from a static context
I got this message while compiling: Hangman- java7; non-static method promptForGuess() cannot be referenced from a static context
A Prompt instance should have been made. I don't see what I'm doing wrong.
This is my code: public class Hangman {
public static void main(String[] args) {
// Enter amazing code here:
Game game = new Game ("Threehouse");
Prompter prompter = new Prompter (game);
boolean isHit = Prompter.promptForGuess();
if (isHit){
System.out.println("We got a hit!");
} else{
System.out.println("Whoops that was a miss");
}
}
}
import java.io.Console;
public class Prompter { private Game mGame;
public Prompter (Game game){
mGame=game;
} public boolean promptForGuess(){ Console console = System.console(); String guessAsString= console.readLine("Enter a letter: "); char guess = guessAsString.charAt(0); return mGame.applyGuess(guess); }
}
public class Game { private String mAnswer; private String mHits; private String mMisses;
public Game(String answer){ mAnswer = answer; mHits = ""; mMisses=""; } public boolean applyGuess(char letter){ boolean isHit= mAnswer.indexOf(letter)>=0;
if (isHit){
mHits += letter;
} else { mMisses += letter; } return isHit; } }
Please, help! Thanks. Regard, Rik-Jan
2 Answers
jcorum
71,830 PointsIt seems you are calling the method on the class rather than the object:
Prompter prompter = new Prompter (game);
boolean isHit = Prompter.promptForGuess();
You have ClassName.methodName() when you need objectName.methodName()
Try boolean isHit = prompter.promptForGuess();
Otherwise, why create the Prompter object?
Rik-Jan van Bree
1,084 PointsGreat! Thx for fast answer. It works!