我正在学习有关递归的Java教程的一部分,我正在寻找一些帮助。在Java中运行递归程序时出现越界异常
我们需要制定一个递归Java程序,该程序可以计算出当没有直飞时如何从一个城市到另一个城市。
我最近的一个问题是,在代码在flightRoute数组列表中有两个城市后,我得到了一个超出界限例外的错误。它会给出错误“IndexOutOfBoundsException Index 2 Size 2”
连接值是一个arrayList,它接受城市连接的所有城市,flightRoute也是一个arrayList,用于跟踪我们必须前往的城市以达到我们的目的地。
我只是不知道为什么它不会继续。
如果可以的话,我将不胜感激。
我不想溢出你们的代码,所以我会提出你应该需要的方法。如果你需要更多,我会愉快地添加更多的代码。
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;
}
你的示例代码使用'i',但不显示它来自哪里......或者你为什么希望能够增加它并要求'Connections.get(i)'withotu问题... –
请堆叠跟踪! –