简体   繁体   中英

How do i change a variable that i have defined in a different class

i have just started java and I was creating a text-based game similar to Zork. but I am having some problems here.

Movement MovementObject = new Movement();

public static void main(String[] args) {

    Room starts;
    starts = new Room();

    starts.Middleroom();


}
public void Middleroom() {
    MovementObject.PlayerSetUp();
    location = "Middleroom"; //here is the problem that i am having it says "location cannot be resolved to a variable"  
    System.out.println("\n\n                   Middleroom ");
    System.out.println("-------------------------------------------------");
    System.out.println("You are in Middleroom to the left there is a very dirty couch.");

}
public void Kitchen() {

    System.out.println("                   \nKitchen\n");
    System.out.println("-----------------------------------------------------\n");
    System.out.println("To the right there is a long staircase that goes to the top floor.\nTo the left there is a kitchen counter.");

this is my first class and my second class is

Scanner myScanner;
String choice;
Room RoomObject = new Room();
String location = null;



public void PlayerSetUp (){
myScanner = new Scanner(System.in);

//here i am making the movement
if(location.equals("Middleroom")) {
    choice = myScanner.nextLine().toLowerCase();
    switch(choice) {
        case"north":
            RoomObject.Kitchen();
            break;
        case"west":
            RoomObject.Familyroom();
            break;
        default:
            System.err.println("\n!!Invalid Input!!\n");
            RoomObject.Middleroom();
            break;     


}
}

if(location.equals("Familyroom")) {
    switch(choice) {

    }
}

the problem i am having is that it wont let me modify location in my first class. i dont know if i am doing it wrong but any advice would help thanks.

Location must be defined in the class as an attribute:

public class Room {
    ...
    private String location;
    ...
}

Then you can expose it to other classes using getters and setters:

public class Room {
    ...
    public String getLocation() { return this.location; }
    public void setLocation(String location) { this.location = location; }
}

You can even use it inside your class (best practice):

public class Room {
  ...
  public void Middleroom() {
    MovementObject.PlayerSetUp();
    this.location("Middleroom"); //same as this.location = "Middleroom"
    ...
  }
  ...
}

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