有 Java 编程相关的问题?

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

java调用二维数组

我还没有完成这段代码,它只是一个模板,我还没有完成对代码的格式化。在另一个类中调用数组的消息部分时遇到问题。我基本上有一个if/else语句,当roomId=some#时,它会从数组中输出与#相关的消息。我只是不知道如何调用数组。Eclipse在“grid”下的if/else语句中向我抛出了一个错误,表示grid无法解析为变量。我还尝试在语句所在的方法中调用数组方法。谢谢你们的帮助

    public class location{
        public int roomId;
        public String name, message;

        public location() {
          roomId = 0;
        }
        public location(String name, int roomId, String message){
          this.name = name;
          this.roomId = roomId;
          this.message = message;
        }
        public void LocArray() {
          location[][] grid = new location[4][4];
          grid [1][0] = new location("LABORATORY", 0, "You're in the lab.");
          grid [2][0] = new location("DUNGEON", 1, "You entered the dungeon.");
          grid [3][0] = new location("COURTYARD ENTRANCE",2,"You have left the dungeon out the backdoor. Either head east and search the courtyard maze, or travel north back to the dungeon");
          grid [3][1] = new location("FIRST PATH", 3,"You have now entered the courtyard, either continue east or move north.");
          grid [3][2] = new location("DEADEND", 4,"You have reached a deadend that has a Magic Shop. Go inside and explore it.");
          grid [3][3] = new location ("MAGIC SHOP", 5, "Search around the Magic Shop and see what there is. When you're done searching continue through the maze.");
          grid [2][1] = new location("SECOND PATH",6,"Search the surroundings for items that will help you get into the locked room, then keep moving.");
          grid [2][2] = new location("END MAZE", 7, "You've made it to the end of the courtyard. There seems to be a cave in the distance; go check it out.");
          grid [1][2] = new location("CAVE",8,"Explore the cave to find the remaining items that will lead to your freedom.");
          grid [0][0] = new location("EXIT",9,"This room will lead to your freedom, but you need the three essential items that will open this door.");
        }
}

 //This is a different class called projectTwo.
 while (stillPlaying) {
    Scanner scan = new Scanner(System.in);
    userInput = scan.nextLine();
    if (roomId == 0){
        if (userInput.equals("n")) {
            System.out.println(grid[2][0].message);
            roomId = 1; // Moves user from location 0 to 1

        }

共 (1) 个答案

  1. # 1 楼答案

    grid变量在locArray方法内声明

    不能在另一个方法或另一个类中的另一个方法中调用它