【问题标题】:I'm trying to call a 2 dimensional array from another class我正在尝试从另一个类调用二维数组
【发布时间】:2015-02-26 03:41:00
【问题描述】:

我们正在尝试使用数组来存储位置,然后在第一类的 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
-------------------------------------------------------------------------

// 这是我们的二维数组类

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());
        }
}
}

【问题讨论】:

  • 为什么在ProjectTwo 类中没有位置类的实例?此外,您的代码格式如此糟糕,令人不安。
  • 在 ProjectTwo 类中实例化 location 类,然后您可以使用 location 对象的引用变量获取数组访问权限。我建议在你的位置类中使用 getter 和 setter,这样你就不会直接修改你的数组数据。
  • 将你的 import 语句从你的类中移出……
  • 看来(如果我错了,请纠正我)您是在要求人们修改您的作业。与其粘贴所有(不是很好的格式)代码并要求一个勺子式的解决方案,为什么不尝试将您的问题分解为一小部分并提出一个更抽象的问题,该问题的解决方案以后可能会使其他人受益?跨度>
  • 实际上我们正在做的是询问如何从不同的类调用数组,以及是否需要使用扩展器来调用另一个类。

标签: java arrays eclipse class methods


【解决方案1】:

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

“尝试使用,L位置而不是l位置来命名类,而不是 nesesario”

打包项目二;

公开课地点{

在您的班级位置:

//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

在你的其他班级:

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://stackoverflow.com/tour

【讨论】:

  • 感谢您的意见!
【解决方案2】:

我绝对同意 cmets 关于代码样式和格式的看法。无论如何,这里是您如何重构代码的建议。

避免编写大量 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

    }
}

...

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

您也可以考虑将这些位置-输入-操作信息存储在某个文件中,对其进行解析,然后在应用/游戏中使用,但实现起来会更加复杂。

【讨论】:

  • 谢谢,非常感谢。我打算对枚举做一些研究以更好地理解它们。
猜你喜欢
  • 1970-01-01
  • 2021-08-14
  • 2013-07-18
  • 2022-12-07
  • 2021-06-04
  • 1970-01-01
  • 2019-06-18
  • 2022-08-12
  • 2012-04-10
相关资源
最近更新 更多