【发布时间】:2011-09-25 13:10:31
【问题描述】:
我正在学习递归作为 Java 教程的一部分,我正在寻求一些帮助。
我们需要编写一个递归 Java 程序,它会计算出在没有直飞航班的情况下如何从一个城市到达另一个城市。
我的问题是我得到了一个似乎只尝试两个城市的无限循环,然后代码一次又一次地重复。
如果可以的话,我将不胜感激。
我不想让你们用代码溢出,所以我会提出你们应该需要的方法。如果您需要更多,我很乐意添加更多代码。
public boolean determineRoute(City from, City to, ArrayList<City> flightRoute) {
int i = 0;
ArrayList<City> Connections = new ArrayList<City>();
// the Connections value takes all the connecting cities we can travel to from a departure point
Connections = from.getConnections();
// searches in the connecting cities from the current city as to if it contains the city we wish to travel to
if (Connections.contains(to)) {
System.out.println("Congrats you can go their cause one of its connecting cities is the to city that u wanna go to");
return true;
} else {
// add connecting city to list for future reference
flightRoute.add(Connections.get(i));
System.out.println(Connections.get(i) + " added to flight route");
// saves current connection
City theCity = Connections.get(i);
// recursive part which sends a new from city for analysis until the city we want to travel to arises
determineRoute(from = Connections.get(i), to, flightRoute);
return true;
}
}
【问题讨论】:
标签: java recursion infinite-loop