作为 Java 教程的一部分,我正在学习递归,我正在寻求一些帮助。
我们需要编写一个递归 Java 程序,它会计算出在没有直飞航班的情况下如何从一个城市到达另一个城市。
我的最新问题是代码在 flightRoute 数组列表中有 2 个城市后出现错误超出范围异常。它给出了错误“IndexOutOfBoundsException Index 2 Size 2”
连接值是一个数组列表,它包含该城市连接的所有城市,而 flightRoute 也是一个数组列表,它跟踪我们为了到达目的地而必须前往的城市。
我只是无法弄清楚为什么它不会继续。
如果可以的话,我将不胜感激。
我不想让你们用代码溢出,所以我会提出你们应该需要的方法。如果您需要更多,我会很乐意添加更多代码。
public boolean determineRoute(City from, City to, ArrayList<City> flightRoute)
{
//the Connections value takes all the connecting cities we can travel to from a departure point
Connections = from.getConnections();
City theCity = Connections.get(i);
//searches in the connecting cities from the current city as to if it contains the city we wish to travel to
if (flightRoute.contains(to)|| 7 >8)
{
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;
}
System.out.println("the City name "+theCity);
if(flightRoute.contains(theCity))
{
System.out.println("Sorry it cannot be added "+Connections.get(i));
}
else
{
//add connecting city to list for future reference
flightRoute.add(Connections.get(i));
//takes the lates connection and uses it for recursion (below)
from = Connections.get(i);
i++;
//recursive part which sends a new from city for analysis until the city we want to travel to arises
determineRoute(from, to, flightRoute);
}
return true;
}