如何更改我在其他类中定义的变量

时间:2017-12-26 16:36:41

标签: java

我刚刚开始java,我正在创建一个类似于Zork的基于文本的游戏。但我在这里遇到了一些问题。

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.");

这是我的第一堂课,第二堂课是

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) {

    }
}

我遇到的问题是它不会让我在第一堂课中修改位置。我不知道我做错了,但任何建议都会有所帮助。

1 个答案:

答案 0 :(得分:1)

位置必须在类中定义为属性:

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

然后,您可以使用getter和setter将其公开给其他类:

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

你甚至可以在课堂上使用它(最佳实践):

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