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