【问题标题】:How to access arraylist from another class for which the main purpose of the class is not the arraylist如何从另一个类的主要目的不是arraylist的类访问arraylist
【发布时间】:2015-03-15 16:43:30
【问题描述】:

我已经阅读了一页又一页的 stackoverflow,试图解决我的问题,并多次修改我的编码,但无济于事。我希望我可以简化我的问题,但我不完全确定我知道我的代码出了什么问题。

我正处于为我正在学习的课程创建游戏的阶段。到目前为止,代码涉及生物的父类和生物类型(动物、NPC 等)的子类,它们是加载的房间,另一个类。我创建了一个 SAXParser 来解析一个 xml 文件,其中包含每个生物和房间的详细信息,以便用每个房间中的房间和生物来填写游戏。我对当前分配的检查是当用户给出它想看到的房间的名称时打印出给定房间的内容。房间保存在 roomArrayList 中。我创建了一个主类,负责处理用户输入。

房间里摆满了正确的东西。当我在解析器中设置“EndElement”方法来打印刚刚创建的房间的内容时,输出是正确的。

但是,当我尝试使用 roomArrayList 根据主类的用户请求打印其中一个房间的内容时,出现异常。我使用 get 方法将数组导入到主类中,如下所示。我可以看出有什么问题,因为当我打印导入数组的大小时,它打印为零。

我不会费心包括生物父类和子类。

这是 MyHandler 类:

public class MyHandler extends DefaultHandler {

    private List<Room> roomList = null;
    private Room r;
    private PC pc;
    private String south, north, west, east;


    ArrayList<Room> roomArrayList = new ArrayList<Room>();

    public ArrayList<Room> getArrayList() {
        return roomArrayList;
    }

    public int checkRoomMatch(String match) {
        int a = -1;
        for (int i = 0; i < roomArrayList.size(); i++) {
            if (roomArrayList.get(i).RoomName.equals(match)) {
                a = i;
            }
        }
        return a;
    }

    public void startDocument() {
        System.out.println("Document parsing started.");
    }

    @Override
    public void startElement(String uri, String localName, String
            qName, Attributes attributes) {

        if (qName.equals("room")) {
            r = new Room(attributes.getValue("name"));
            r.setDescription(attributes.getValue("description"));
            r.setState(attributes.getValue("state"));
            north = attributes.getValue("north");
            west = attributes.getValue("west");
            east = attributes.getValue("east");
            south = attributes.getValue("south");

            r.setNeighbor(south, north, east, west, roomArrayList);

            roomArrayList.add(r);
        }
        else if (qName.equals("animal")) {
            Animal animal = new Animal
                    (attributes.getValue("name"), attributes.getValue("description"),
                            r, qName);
            r.addCreature(animal);
        }
        else if (qName.equals("NPC")) {
            NPC npc = new NPC(attributes.getValue("name"),
                    attributes.getValue("description"), r, qName);
            r.addCreature(npc);
        }
        else if (qName.equals("PC")) {
            pc = new PC(attributes.getValue("name"),
                    attributes.getValue("description"), r, qName);
            r.addCreature(pc);
        }
    }

    public void endElement(String uri,
                           String localName,
                           String qName) {

        if (qName.equals("room")) {
            System.out.println(r.toString());
        }
    }

    public void endDocument() {
        System.out.println("Document parsing ended.");
    }
}

这是我的 Room 类:

public class Room {

    Creature[] CreatureArray = new Creature[10];
    String RoomName;
    private int CreatureCount = 0;
    String description;
    String currentState;
    final String Dirty = "dirty";
    final String HalfDirty = "half-dirty";
    final String Clean = "clean";

    // 0 is north, 1 is east, 2 is south, 3 is west
    private Room[] roomArray = new Room[4];

    public Room(String name) {
        RoomName = name;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setState(String state) {
        this.currentState = state;
    }

    public String getName() {
        return RoomName;
    }

    public String toString() {
        String roomInfo = "";
        roomInfo += "This room is called" + RoomName + "." + "\n";
        roomInfo += "The following animals are in this room: ";
        for (int x = 0; x < CreatureCount; x++) {
            roomInfo += CreatureArray[x].toString();

            if (x < CreatureCount - 1) {
            }
        }

        roomInfo += "\n" + "The description for room " + RoomName + " is: 
        " + description + ". " + "\n ";
        roomInfo += "The current state of room " + RoomName + " is " +
                currentState + "." + "\n";
        roomInfo += "Room " + RoomName + " is positioned with room " +
                "roomArray[0]" + " to the north, room "
                + "roomArray[1]" + " to the east, room " + "roomArray[2]"
                + " to the south and room "
                + "roomArray[3]" + " to the west." + "\n";

        return roomInfo;
    }

    public void addCreature(Creature a) {
        if (CreatureCount < 10) {
            CreatureArray[CreatureCount] = a;
            CreatureCount++;
        }
        else {
            System.out.println("This room is full.");
        }
    }

    public void setNeighbor(String south, String north, String east,
                            String west, ArrayList<Room> roomArrayList) {

        if (roomArrayList.size() >= 1) {
            for (int i = 0; i < roomArrayList.size(); i++) {
                if (roomArrayList.get(i).RoomName.equals(north)) {
                    roomArray[0] = roomArrayList.get(i);
                    roomArrayList.get(i).roomArray[2] = this;
                    continue;
                }

                if (roomArrayList.get(i).RoomName.equals(south)) {
                    roomArray[2] = roomArrayList.get(i);
                    roomArrayList.get(i).roomArray[0] = this;
                    continue;
                }

                if (roomArrayList.get(i).RoomName.equals(east)) {
                    roomArray[1] = roomArrayList.get(i);
                    roomArrayList.get(i).roomArray[3] = this;
                    continue;
                }

                if (roomArrayList.get(i).RoomName.equals(west)) {
                    roomArray[3] = roomArrayList.get(i);
                    roomArrayList.get(i).roomArray[1] = this;
                    continue;
                }
            }
        }
    }
}

这是处理用户输入的主要方法。我已经注释掉了打印导入数组大小的命令。但请记住,当该行运行时,输出为零。它下面的 println 命令是应该可以打印所选房间内容的函数。

public class Main {

    public static void main(String[] a) throws Exception {
        File f;
        Scanner fs = null;

        Scanner kb = new Scanner(System.in);
        System.out.println("Enter a file name:");

        String fileName = kb.nextLine();

        f = new File(fileName);

        if (!f.exists()) {
            System.out.println("File not found. Please try again.");
            System.out.println("Enter a file name:");
        }

        SAXParserFactory factory = SAXParserFactory.newInstance();

        MyHandler handler = new MyHandler();
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(fileName, new MyHandler());

        System.out.println("Enter the name of a room for which you would " +
                "like to see the contents.");

        String selectedRoom = kb.nextLine();

        ArrayList<Room> roomArrayList = handler.getArrayList();

        int roomIndex = handler.checkRoomMatch(selectedRoom);
        while (roomIndex == -1) {
            System.out.println("No such room existed in the input file.");
            System.out.println("Enter the name of a room for which you " +
                    "would like to see the contents.");
            selectedRoom = kb.nextLine();

            roomIndex = handler.checkRoomMatch(selectedRoom);
        }
        //        System.out.println(roomArrayList.size());
        System.out.println(roomArrayList.get(roomIndex).toString());
    }
}

我希望我已经正确地提出了这个问题。这是我第一次提出问题,因为我真的觉得我已经耗尽了我的资源。

tl;dr -- 为什么我的填充 roomArrayList 没有被导入到我的 main 方法中?

【问题讨论】:

  • 您所做的是一个很好的解决方案 - 只需添加一个“getter”方法。建议:将方法名称从“public ArrayList getArrayList()”更改为“public List&lt;Room&gt; getRooms() {...}”。

标签: java arraylist import get tostring


【解决方案1】:

您将 MyHandler 的一个新实例传递给 Parser,在该实例中,您的数组列表将被填充,而不是在您现有的处理程序实例中,因此它保持为空。

所以不要传递新的处理程序,而是使用现有的处理程序,例如:

saxParser.parse(fileName, new MyHandler());

用途:

saxParser.parse(fileName, handler);//now handler will be having array list populated with rooms and you could use it further.

【讨论】:

  • :哇!那解决了它!非常感谢你。我欠债了!
猜你喜欢
  • 2016-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-17
相关资源
最近更新 更多