2011-09-26 105 views
0

我正在学习有关递归的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;  
     } 
+0

你的示例代码使用'i',但不显示它来自哪里......或者你为什么希望能够增加它并要求'Connections.get(i)'withotu问题... –

+0

请堆叠跟踪! –

回答

0

你在哪里设置i值?无论如何,只有get()您使用i作为索引,因此很显然Connections没有像i那样多的项目。 BTW

:代替connectionsConnections

变量名的)下一个时间标记,在哪一行抛出异常(从我所看到的,probaly第一get()

B)使用小写

+0

我在文件开头初始化,如\t private int flightRouteSize,i = 0; 并在城市上抛出异常theCity = Connections.get(i); 以及递归方法本身 – Binyomin

+0

是的,它是第一个得到。 – Binyomin

+0

既然你总是增加我,我敢打赌,在代码的其他部分,你会得到这个错误是比平常更多... 你需要在这个代码中实例化变量i,这样每当它被称为重置为0,你也应该在循环中运行这个代码。 –

0

问题是i本地声明,所以你永远增加一些实例变量。在本地声明并将其设置为零。拥有国内领先的小写

  • 名称变量 - 即connectionsConnections
  • 使用局部变量的地方是有道理的 - :

    之前,你可以做任何真正的进步解决这个代码,我劝你清理像connections

  • 删除无意义的代码,如测试如果7 > 8为真 - 当然是总是是真的!
  • 使用超过使用“foreach”循环集合块
  • 迭代的正确的缩进:for (City city : from.getConnections())
  • 倾向于命名变量一样的类名,但有一个小写字母,所以city,不theCity
+0

感谢您的帮助我将修复我的代码并使其更易于阅读,它的好处是您告诉我这一点,因为我希望以正确的方式进行编码,并且只有其他人告诉我我会出错哪里。 关于代码,我会更好地消除我的计数器,并完成?我已经看了很久以前的这段代码,真不知道怎么回事。 :) – Binyomin