在Java中运行递归程序时出现越界异常
我正在学习有关递归的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
值?无论如何,只有get()
您使用i
作为索引,因此很显然Connections
没有像i
那样多的项目。 BTW
:代替connections
Connections
变量名的)下一个时间标记,在哪一行抛出异常(从我所看到的,probaly第一get()
B)使用小写
问题是i
是非本地声明,所以你永远增加一些实例变量。在本地声明并将其设置为零。拥有国内领先的小写
- 名称变量 - 即
connections
不Connections
- 使用局部变量的地方是有道理的 - :
之前,你可以做任何真正的进步解决这个代码,我劝你清理像
connections
- 删除无意义的代码,如测试如果
7 > 8
为真 - 当然是总是是真的! - 使用超过使用“foreach”循环集合块
- 迭代的正确的缩进:
for (City city : from.getConnections())
- 倾向于命名变量一样的类名,但有一个小写字母,所以
city
,不theCity
感谢您的帮助我将修复我的代码并使其更易于阅读,它的好处是您告诉我这一点,因为我希望以正确的方式进行编码,并且只有其他人告诉我我会出错哪里。 关于代码,我会更好地消除我的计数器,并完成?我已经看了很久以前的这段代码,真不知道怎么回事。 :) – Binyomin
你的示例代码使用'i',但不显示它来自哪里......或者你为什么希望能够增加它并要求'Connections.get(i)'withotu问题... –
请堆叠跟踪! –