Question: I am getting an error - Exception in thread main java.lang.NullPointerException: Cannot invoke Location.getName() because this.locations[this.currentLocation] is null at Game.play(Game.java:60) at Wonderland.main(wonderland.java:18). This is my

I am getting an error -

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Location.getName()" because "this.locations[this.currentLocation]" is null at Game.play(Game.java:60) at Wonderland.main(wonderland.java:18).

This is my code:

public class Game extends Wonderland { // Declare and initialize global variables private static final int NUM_LOCATIONS = 5; private static final int NUM_CHARACTERS = 5; private static final int NUM_ITEMS = 12; private Location[] locations; private Character[] characters; private Item[] items; private int currentLocation; // Default constructor public Game() { // Create the array of locations locations = new Location[NUM_LOCATIONS]; // Create the array of characters characters = new Character[NUM_CHARACTERS]; // Create the array of items items = new Item[NUM_ITEMS]; // Initialize the game by populating the arrays // with objects initGame(); // Set the current location to the starting location currentLocation = 0; } // Method to initialize the game by populating the // arrays with objects private void initGame() {

// Create the locations String[] locations = {"north", "east", "west", "south", "safe area"}; // Create the characters String[] characters = {"Ceshire Cat", "Mad Hatter", "Red Queen", "The Duchess", "The Caterpillar"};

// Create the items String[] items = {"Rabbit's Watch", "Cookies", "Sword", "Potion", "Flashlight", "Jewel", "Golden Key", "Magic Broom", "Red Shoes", "Magic Cloth", "A Little Dragon", "A Cloak"}; } // Method to play the game public void play() { // Print the opening message System.out.println(" You are now playing Wonderland."); // Print the current location System.out.println("You are currently in " + locations[currentLocation].getName()); // Print the current location description System.out.println(locations[currentLocation].getDescription()); play();

} }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!