簡體   English   中英

我如何更改我在不同類中定義的變量

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

我剛剛開始使用 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) {

    }
}

我遇到的問題是它不會讓我在第一堂課上修改位置。 我不知道我是否做錯了,但任何建議都會有所幫助,謝謝。

位置必須在類中定義為屬性:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM