这是我正在进行的一个小冒险游戏。我只是试图创建一个3x3矩阵,玩家可以在其中移动。但是,在游戏循环中(我还没有循环,我知道),我无法引用播放器或我用init()方法创建的房间对象。 (我有Player和Room对象的单独类文件,它们工作正常。)当我尝试运行此代码时:
import java.util.Scanner;
public class Adventure
{
public final static int maxCol = 2;
public final static int maxRow = 2;
public static void init()
{
Scanner keyboard = new Scanner(System.in);
//instantiate rooms
final Room[][] maze = new Room[maxCol+1][maxRow+1];
final Player player = new Player("",1,1);
for(int i = 0; i <= maxCol; i++)
{
for(int j = 0; j <= maxRow; j++)
{
maze[i][j] = new Room("room");
}
}
//room names
maze[0][0].setDesc("Alleyway - West");
maze[0][1].setDesc("Alleyway - East");
maze[0][2].setDesc("Back Entrance");
maze[1][0].setDesc("Back Room");
maze[1][1].setDesc("Hallway");
maze[1][2].setDesc("Bar - North");
maze[2][0].setDesc("Bathroom");
maze[2][1].setDesc("By An Arcade Machine");
maze[2][2].setDesc("Bar - South");
//get player name
System.out.print("What is your name? ");
String nameInput = keyboard.nextLine();
//create player object
player.setName(nameInput);
player.display();
}
public static void main(String args[])
{
init();
playGame();
}
public static void playGame()
{
System.out.print(maze[player.getXPos()][player.getYPos()].getDesc());
}
}
我收到这些错误:
Adventure.java:54: error: cannot find symbol
System.out.print(maze[player.getXPos()][player.getYPos()].getDesc());
^ symbol: variable maze location: class Adventure Adventure.java:54: error: cannot find symbol
System.out.print(maze[player.getXPos()][player.getYPos()].getDesc());
^ symbol: variable player location: class Adventure Adventure.java:54: error: cannot find symbol
System.out.print(maze[player.getXPos()][player.getYPos()].getDesc());
^ symbol: variable player location: class Adventure 3 errors
我做错了什么?谢谢:))
答案 0 :(得分:0)
maze
变量的范围仅限于方法init
,因此无法在playGame
方法中找到它。更新init
以返回迷宫(Room[][]
)或将其声明为静态。实际上,您也需要为player
对象执行此操作。
答案 1 :(得分:0)
这是一个范围问题! Java具有如何可以访问某些内容的特定规则,具体取决于声明它的 where 。如果在方法中声明了某些内容,那么只能在该方法中访问它。
public void doSomething() {
String str = "Hello";
// when doSomething ends, str is lost!
}
要解决此问题,您可以在全局级别的方法之外声明您的变量。
String str = "Hello";
public void doSomething() {
str = "Hello";
}
请注意,您已在方法之外宣布,但您已在方法内定义它。
额外阅读