我正在尝试从另一个 class 调用二维数组

I'm trying to call a 2 dimensional array from another class

我们正在尝试使用数组来存储位置,然后在第一个 class 的 if else 语句中调用它们。我们希望能够调用网格位置,这样我们就不必在 if else 语句中键入房间的描述。

package ProjectTwo;   
import java.util.Scanner;
public class ProjectTwo {
    // ----------------------------------------
    // Main method, calls location (loc) method, which controls navigation
    // ----------------------------------------
    public static void main(String[] args){
       loc();
    }
    // This method allows the user to view a list of actions that are used throughout the game
    public static void help() {
        System.out.println("Enter the letter 'n' to move north, the letter 's' to move south, or type the word 'quit' to end the game. Also, you can enter the letter 'm' to see an image of the map.");
    }
    // -------------------------------------
    // Loc method
    // Prints on-load message (intro)
    // Defines global variables
    // -------------------------------------
    public static void loc() {
        location.locMove();

        int location = 0;
        System.out.println("The Search" + "\n" + "\n" + "You have awoken in a laboratory. There is a door to your north and a door to your south." + "/n+" +  "Enter 'n' and 's' to navigate, or type 'quit' to end the game. Also, enter the letter 'h'.");

        String userInput = new String();
        boolean stillPlaying = true;
    // ------------------------------------ 
    // Moves player while user is still playing
    // Tells user his/her location  
    // ------------------------------------
    while (stillPlaying) {
        Scanner scan = new Scanner(System.in);
        userInput = scan.nextLine();
        if (location == 0){
            if (userInput.equals("n")) {
                System.out.println("You entered the dungeon.");
                location = 1; // Moves user from location 0 to 1

            }
                else if (userInput.equals("s")) {
                System.out.println("You cannot move south.");
                location = 0; // Keeps user at location 0
                } else if (userInput.equals("quit")){
                    System.out.println("Thanks for playing");
                    stillPlaying = false;
        }
                else if (userInput.equals("h")) {
                    help(); // calls the help method
                }
                else if (userInput.equals("m")) {
                    map(); // calls the map method
                }
            else {
                System.out.println("Command not understood.");  

            } 

        }   else if (location == 1) {
            if (userInput.equals("n")) {
                System.out.println("You have escaped out the back door of the dungeon.");
                location = 2; // Moves user from location 1 to location 2
            }
            else if(userInput.equals("s")) {
                System.out.println("You're back in the laboratory.");
                location = 0; // Moves user from location 1 to location 0
            } else if (userInput.equals("quit")){
                System.out.println("Thanks for playing");
                stillPlaying = false;
            }
            else if (userInput.equals("h")) {
                help(); // calls the help method
            }
            else if (userInput.equals("m")) {
                map(); // calls the map method
            }
            else {
                System.out.println("Command not understood");

            }
        }

        else if (location == 2) {
            if (userInput.equals("n")) {
                System.out.println("You cannot go that way...yet!");
                location = 2; // Lets the user know that they cannot go that way

            }
            else if (userInput.equals("s")) {
                System.out.println("You're back in the dungeon");
                location = 1; // Mover from location 2 to location 1
                }
        else if (userInput.equals("quit")){
                    System.out.println("Thanks for playing");
                    stillPlaying = false;
                    }
        else if (userInput.equals("h")) {
            help(); // calls help method
        }
        else if (userInput.equals("m")) {
            map(); // calls map method
        }
        else {
                System.out.println("Command not understood.");

                }
        }


    }
}
}

//This is our main class
-------------------------------------------------------------------------

// 这是我们的 class 和二维数组

package ProjectTwo;
public class location {

        public int location;
        public String name;
        public static String message;

        public location(String name, int location, String message){
            this.name = name;
            this.location = location;
            this.message = message;

            System.out.println(message);
        }
        public static void locMove() {
        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.");
        }
        while (grid.equals(0)) {
            System.out.println(message.toString());
        }
}
}

有很多方法可以按照你说的去做,但看看你的代码,认为这真的很适合你的代码,没有太多改变,但只是我的意见:

"尝试使用 L位置而不是 l位置来命名 classes 但不是 nesesario “

package ProjectTwo;

public class location {

在您的 Class 位置:

//Your other code

public static location [][] locMove() {  // <--- change void for location [][]
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.");
        }
    while (grid.equals(0)) {
        System.out.println(message.toString());
    }

 return grid;
 }

 //Your other code

在你的另一个 class:

package ProjectTwo;   
public class ProjectTwo {
    //your other code
    location [][] testGrid = null; //<--- add variable
    //your other code

    public static void main(String[] args){
           loc();
}
   //your other code

    public static void loc() {

        testGrid = location.locMove();

        //testGrid <-- this your array
  //your other code

我没有测试过,但我认为它可以工作,但不是我通常做的方式,希望你能帮忙。

P.S:你可以看看这个,如果你想https://whosebug.com/tour

我完全同意关于代码风格和格式的评论。无论如何,这里是关于如何重构代码的建议。

避免编写大量 if-else 结构的最简单方法可能是使用开关。你的 loc() 代码可能看起来像那样(我也会将重复的 h/m/quit 命令移动到一个地方):

解决方案 1:

...

while (stillPlaying) {
    Scanner scan = new Scanner(System.in);
    userInput = scan.nextLine();

    switch (userInput) {
        case "quit":
            System.out.println("Thanks for playing");
            stillPlaying = false;
            break;

        case "h":
            help(); // calls the help method
            break;

        case "m":
            map(); // calls the map method
            break;

        case "n":
        case "s":
            switch (location) {
                case 0:
                    switch (userInput) {
                        case "n":
                            System.out.println("You entered the dungeon.");
                            location = 1; // Moves user from location 0 to 1
                            break;

                        case "s":
                            System.out.println("You cannot move south.");
                            location = 0; // Keeps user at location 0
                            break;
                    }
                    break;

                case 1:
                    switch (userInput) {
                        case "n":
                            System.out.println("You have escaped out the back door of the dungeon.");
                            location = 2; // Moves user from location 1 to location 2
                            break;

                        case "s":
                            System.out.println("You're back in the laboratory.");
                            location = 0; // Moves user from location 1 to location 0
                            break;
                    }
                    break;

                case 2:
                    switch (userInput) {
                        case "n":
                            System.out.println("You cannot go that way...yet!");
                            location = 2; // Lets the user know that they cannot go that way
                            break;

                        case "s":
                            System.out.println("You're back in the dungeon");
                            location = 1; // Mover from location 2 to location 1
                            break;
                    }
                    break;

                default:
                    System.out.println("no such location");
            }
            break;

        default:
            System.out.println("Command not understood.");

    }
}

...

然而,更好的方法是尝试将位置-命令-操作内容封装到不同的 类。它可能看起来如何:

解决方案 2:

public static interface Action {
    // return the next location or an error
    int action();
}

public static class LocationsMap {
    public Map<Integer, Map<String, Action>> locations = new HashMap<>();

    public void registerAction(int location, String userInput, Action action) {
        Map<String, Action> actionsMap = locations.get(location);
        if (actionsMap == null) {
            actionsMap = new HashMap<>();
            locations.put(location, actionsMap);
        }

        actionsMap.put(userInput, action);
    }

    public int executeAction(int location, String userInput) {
        Map<String, Action> currentLocation = locations.get(location);
        if (currentLocation == null) {
            return -1;
        }

        Action currentAction = currentLocation.get(userInput);
        if (currentAction == null) {
            return -2;
        }

        return currentAction.action(); // move to next location
    }
}

然后您可以像这样定义您的操作(每个位置和用户输入):

...

public static LocationsMap locationsMap = new LocationsMap();
static {
    // location 0
    locationsMap.registerAction(0, "n", new Action() {
        @Override
        public int action() {
            System.out.println("You entered the dungeon.");
            return  1; // Moves user from location 0 to 1
        }
    });
    locationsMap.registerAction(0, "s", new Action() {
        @Override
        public int action() {
            System.out.println("You cannot move south.");
            return  0; // Keeps user at location 0
        }
    });

    // location 1
    locationsMap.registerAction(1, "n", new Action() {
        @Override
        public int action() {
            System.out.println("You have escaped out the back door of the dungeon.");
            return 2; // Moves user from location 1 to location 2
        }
    });
    locationsMap.registerAction(1, "s", new Action() {
        @Override
        public int action() {
            System.out.println("You're back in the laboratory.");
            return 0; // Moves user from location 1 to location 0
        }
    });

    // location 2
    locationsMap.registerAction(2, "n", new Action() {
        @Override
        public int action() {
            System.out.println("You cannot go that way...yet!");
            return 2; // Lets the user know that they cannot go that way
        }
    });
    locationsMap.registerAction(2, "s", new Action() {
        @Override
        public int action() {
            System.out.println("You're back in the dungeon");
            return 1; // Mover from location 2 to location 1
        }
    });
}

...

然后 loc() 函数中的代码将如下所示:

...

while (stillPlaying) {
    Scanner scan = new Scanner(System.in);
    userInput = scan.nextLine();

    switch (userInput) {
        case "quit":
            System.out.println("Thanks for playing");
            stillPlaying = false;
            break;

        case "h":
            help(); // calls the help method
            break;

        case "m":
            map(); // calls the map method
            break;

        default:
            int actionResult = locationsMap.executeAction(location, userInput);

            if (actionResult == -1) {
                System.out.println("no such location");
                break;
            }

            if (actionResult == -2) {
                System.out.println("Command not understood.");
                break;
            }

            location = actionResult; // move to next location

    }
}

...

这不是最好的解决方案,但它更好且可读性更好。 我还会为位置定义一个枚举,而不是使用整数。

您也可以考虑将此位置-输入-操作信息存储在某个文件中,解析它然后在 app/game 中使用,但实现起来会更复杂。