简体   繁体   中英

How to access variables from another method

I have a class named "Game" in Java, and the aim/goal is to reach a certain room, the "throne" room. When the throne room is reached the game ends.

public class Game {

    // fields

    private Room currentRoom;
    private boolean finished;
    private Room throne;

    /**
     * Create the game and initialise its internal map.
     */
    public Game() 
    {
        finished = false;
        createRooms();
    }

    /**
     * Create all the rooms and link their exits together.
     */
    private void createRooms()
    {
        Room gate, graveyard, church, crypt, entrance, hall, kitchen, buttery, greathall, staircase,
        dungeon, topstaircase, throne, solar, wardrobe, privy;

        // create the rooms
        gate = new Room("outside the old gate of the castle");
        graveyard = new Room("on a wind-swept gaveyard");
        church = new Room("in a small ancient church");
        throne = new Room("in the throne room with golden walls");
        // other rooms ...

        // initialize room exits

        gate.setExit("north", graveyard);
        throne.setExit("south", topstaircase);
        // other exits ...
    }
}

To go in one direction/room :

public String goRoom(String direction) 
{
    assert direction != null : "Game.goRoom gets null direction";

    // Try to leave current room.
    Room nextRoom = currentRoom.getExit(direction);
    if (nextRoom == null) {
        return "There is no exit in that direction!";
    } else {
        currentRoom = nextRoom;
        return currentRoom.getLongDescription();
    }
}

To go into a specific room to end the game ie "throne" room here's what I did :

    if (currentRoom.equals(throne)) {
        finished = true;
        return "Congrats you have reached the throne room";
    }

But I keep getting this error : cannot find symbol - variable throne

This is a project based on the "Object first with Java using blueJ"

Instead of declaring the Room throne in your private void createRooms() , you can declare it as a field, so right after the constructor you can say Room throne; , you can then still initialize it in your createRooms method.

You could consider making it final because it won't change anymore and that clearly states the intention

In this case I wouldn't pass it to the next parameter, to me it would make sense to have it as a field

Edit: on the topic of your unreachable statement comment, what I suspect you're doing is checking for the finished state of the game after your following code:

} else {
        currentRoom = nextRoom;
        return currentRoom.getLongDescription();
    }

Because you're already returning from the method here, you're never actually checking for the end state of the game.

You are storing your Room s as local variables. These variables are deleted as soon as your method terminates, so the Room s will disappear.

To solve this, you should declare your variables at the class level:

public class Game {
    private Room currentRoom;
    private boolean finished;
    private Room Goal;
    private Map<String, Room> rooms;


public Game() {
    finished = false;
    rooms = new HashMap<>();
    createRooms();
}

//....

private void createRooms() {
    rooms.put("gate", new Room("outside the old gate at the castle"));
    //similar for other rooms
    //...
}

Then, you can access your rooms by defining a function

public Room getRoom(String roomName) {
    if (rooms.containsKey(roomName))
        return rooms.get(roomName);
    throw new IllegalArgumentException("No such room: " + roomName);
}

For example:

if (currentRoom.equals(getRoom("throne")) {

        finished = true;
        return "Congrats you have reached the throne room";
}

If goRoom() is not in Game , you will need to get an instance of Game first, and then call getRoom() on that instance.

But I keep getting this error : "cannot find symbol - variable throne". I believe i need a field somewhere but I am unsure where and how this is useful.

You are getting this error because variable throne is a local variable whose scope is just inside the method it is declared

private void createRooms()
{
    Room gate, graveyard, church, crypt, entrance, hall, kitchen, buttery, greathall, staircase,
        dungeon, topstaircase, throne, solar, wardrobe, privy;


    // create the rooms
    gate = new Room("outside the old gate of the castle");
    graveyard = new Room("on a wind-swept gaveyard");
    church = new Room("in a small ancient church");
    throne = new Room("in the throne room with golden walls");// local variable
    // other rooms ...

    // initialise room exits

    gate.setExit("north", graveyard);
    throne.setExit("south", topstaircase);
    // other exits ...
    }

Now Instead of making it local you can make it as instance variable or class variable so it can be accessible , if you wish to make this variable as private instance variable then provide getters and setters to access this variable's value .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM