BlueBear
BlueBear

Reputation: 7639

Referencing another class as an Instance Variable?

I am looking for some help with utilizing methods from another class in Java. I have created a class that has some getter and setter methods. The getter method contains a switch statement that has a passed in parameter "i" that determines the case of the switch statement.

Now in my main program I am looking to use that class method, but for some reason I am getting a java.lang.nullpointerexception.

The code in my main program looks like this:

public class Hangman extends ConsoleProgram {

    public void run() {

        String name = word.getWord(5);

        println(name);
    }



    /* Private Instance Variable */
    private HangmanLexicon word; // Creates a new lexicon from the HangmanLexicon class.
    private RandomGenerator rgen = RandomGenerator.getInstance(); // Creates a new random generator instance.

}

So as you can tell I created the private ivar, but for some reason it does not work. Any help would be great! Thanks!

Upvotes: 1

Views: 350

Answers (4)

nsgulliver
nsgulliver

Reputation: 12671

Reason for NullPointerException occurs because word has no value assigned. You must assign value to word first before using it to call the method getWord(5);

private HangmanLexicon word;
                        ^

initialize or assign word like this instead as follows

private HangmanLexicon word=new HangmanLexicon();

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 692191

You haven't initialized the word variable. So it has the default value: null. And calling a method on a null object cause a NullPointerException.

Read a good book about Java, or the Java tutorial. This is basic stuff you need to understand.

Upvotes: 1

Joni
Joni

Reputation: 111389

Creating the variable us not enough: you have to assign something to it, too.

private HangmanLexicon word = /*put something here*/;

Upvotes: 1

Lee Meador
Lee Meador

Reputation: 12985

In the code you show word is never given a value so it will be null

You might need something like:

 private HangmanLexicon word = new HangmanLexicon();

Or you might need to get a HangmanLexicon object to put in your instance variable some other way.

Note If you are doing this for a Stanford CS class (or similar university class) I found the source of the HangmanLexicon online by searching. The line above would work if AND ONLY IF that is the same code as what I found.

Upvotes: 1

Related Questions