java - 如何使用 .next() 迭代对象映射?

标签 java object dictionary iterator

我在 Location 类中实现了 Iterable,该类存储对象 map ,以允许迭代 map 中的每个对象。

但是当我测试这段代码时,只加载了第一个位置,即“Tiberius” 当我输入一个移动命令时。

有人知道为什么在此实现中没有加载 map 中的下一个位置吗?

这是添加位置的 map 和迭代器方法:

private Map<Location, Integer> children = new HashMap<Location, Integer>();



        @Override
        public Iterator<Location> iterator() {
             return children.keySet().iterator();
        }

在起始位置调用 .next() 的主类:

public class Main {

    public static void main(String[] args)  {

        //Boolean to signify game state 
        boolean gameNotOver = true;

        Location nextLocation = new Location();
        Location startNode = new Location();

        Iterator<Location> nodeIterator = startNode.iterator();


        GameMap playerMap = new GameMap();
        playerMap.getStartNode();

        //get the first location in the map
        startNode = playerMap.getStartNode();

        //main game loop
        while (gameNotOver) {

            Main mainObj = new Main();

            //Take in user commands here
            //and parse commands
            String input = Input.getInput();
            if (input.equals("description")) {
                System.out.println("Description: " );
            } else if (input.equals("move")) {
                System.out.println("Moving.. " );
                //call the next location in the map
                startNode.next();
                System.out.println(startNode.toString());
            //Invalid input check
            else {
                System.out.println("Invalid command, try again!");
            }

        }

        //Game over 
        System.out.println("Game Over!");
        System.exit(0);
    }

}

最佳答案

您正在使用

startNode.next();
System.out.println(startNode.toString());

但是你永远不会改变startNode。难怪为什么总是打印相同的位置。将此代码更改为

startNode = startNode.next();
System.out.println(startNode.toString());

它应该可以工作。

关于java - 如何使用 .next() 迭代对象映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29590226/

相关文章:

java - 如何在 TERRIER 信息检索系统中使用 YASS 或 GRAS 等统计词干分析器代替 Porter 词干分析器

java - 无法创建 JFrame 的屏幕截图

java - 什么是组件

javascript - 在转换日期时从数组到带有服装键的对象

java - 将历史记录存储在数据库中

java - 为什么删除动态数组末尾的项目 O(n) 时间复杂度?

java - 找不到类 'org.apache.http.entity.mime.content.Filebody',从方法中引用

JavaScript 对象关联

python - 在字典中打印键值对时,它们是否以任何特定顺序打印? (Python)

python : How to get sum of all values until a specific key is reached in dictionary