有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 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"
        ...
      }
      ...
    }