I am currently a beginner in Java programming and was tasked to "Code and test a version of the Hangman game. Your solution will involve a Hangman class whose constructor chooses a word, and whose guess method processes each guessed character."
However, I have one little problem. My entire code works and compiles and I have already written the guess method, but I have a problem compiling. I declare my instance variables inside of my constructor. I use the String variable word in my code at various places, and it does not let me compile.
The heart of my problem is this.
public class Hangman{
public Hangman () {
String word = "p u m p k i n";
String blanks = "_ _ _ _ _ _ _";
}
int k = word.length(); ... rest code after this
When I try to compile this, it does not let me. It says that variable word is null and displays an error message. Why can't I use word.length() to find the value of the length? Is it not possible to use the variables declared inside of the constructor as instance variables? The easiest workaround to this is to declare my instance variables outside of the constructor (my code works flawlessly if I do), but the prompt wants me to choose the declare the word inside the constructor.Why can't I use the String word that I declared as "p u m p k i n" inside of the constructor to get k? Using the variable blanks inside of my method does not work either.
So, what is wrong with this? How can I use the variables declared in the constructor as instance variables? Or is this not possible? Why can't I use the String word or String blanks declared in the constructor? Thanks.
Each time you are creating the local variables in constructor.
public Hangman () {
String word = "p u m p k i n";
String blanks = "_ _ _ _ _ _ _";
}
What you have to do is Assign values in constructor
to the members.
String word;
String blanks;
public Hangman () {
word = "p u m p k i n";
blanks = "_ _ _ _ _ _ _";
}
More over it doesn't make sense that not getting them in constructor args and assign them in constructor.
It should be
public Hangman (String word, String blanks) {
this.word = word;
this.blanks = blanks;
}
Declare them as instance variables and initialize them in the Constructor. If you declare and initialize them in the constructor, they'll will be accessible only within the constructor(local scope) and wouldn't be accessible elsewhere, thus rendering them, useless.
private String word;
private String blanks;
public Hangman () {
word = "p u m p k i n";
blanks = "_ _ _ _ _ _ _";
}
// Have setters and getters for word and blanks if possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With