Quantcast
Channel: Variables in Constructor? - Stack Overflow
Viewing all articles
Browse latest Browse all 5

Variables in Constructor?

$
0
0

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.


Viewing all articles
Browse latest Browse all 5

Latest Images

Trending Articles





Latest Images