[英]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.我刚刚开始使用 Java,我正在创建一个类似于 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:然后,您可以使用 getter 和 setter 将其公开给其他类:
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"
...
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.