0

作为 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;    
        }
4

2 回答 2

0

你在哪里设置i值?无论如何,唯一get()你使用i的索引,所以很明显它Connections没有像i.

顺便提一句:

a)下一次标记在哪一行抛出异常(从我所见,可能是第一个get()

b) 使用小写的变量名:connections而不是Connections

于 2011-09-26T10:14:04.440 回答
0

问题是它i没有本地声明,所以你永远在增加一些实例变量。在本地声明它并将其设置为零。

在修复此代码取得任何实际进展之前,我建议您清理它:

  • 使用前导小写命名变量 - 即connections不是Connections
  • 在有意义的地方使用局部变量——比如connections
  • 删除无意义的代码,例如测试 if 是否7 > 8为真——当然它总是正确的!
  • 使用适当的块缩进
  • 使用“foreach”循环遍历集合:for (City city : from.getConnections())
  • 倾向于将变量命名为与类名相同的名称,但使用小写字母,因此city,而不是theCity
于 2011-09-26T10:25:06.710 回答