0

Java チュートリアルの一部として再帰について学んでおり、少し助けを求めています。

直行便がない場合に、ある都市から別の都市に移動する方法を解決する再帰的な Java プログラムを作成する必要があります。

私の最新の問題は、コードの FlightRoute 配列リストに 2 つの都市が含まれていると、範囲外の例外でエラーが発生することです。「IndexOutOfBoundsException Index 2 Size 2」というエラーが発生します

connection 値は、その都市が接続するすべての都市を取得する 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;    
        }
4

2 に答える 2

0

値をどこに設定しiますか? とにかく、インデックスとしてget()使用するのは だけなので、が ほど多くのアイテムを持っていないiことは明らかです。Connectionsi

ところで:

a)次回、例外がスローされる行をマークします(私が見たところ、おそらく最初のget()

b) 変数名には小文字を使用します:connections代わりにConnections

于 2011-09-26T10:14:04.440 に答える
0

問題は、ローカルで宣言されてiないため、インスタンス変数を永久にインクリメントしていることです。ローカルで宣言し、ゼロに設定します。

このコードを修正する前に、コードをクリーンアップすることをお勧めします。

  • 先頭に小文字を使用して変数に名前を付けます-つまり、そうでconnectionsはありませんConnections
  • 意味のある場所でローカル変数を使用する - のようにconnections
  • 7 > 8テスト if is trueなどの無意味なコードを削除します - もちろん常にtrue です!
  • ブロックの適切なインデントを使用する
  • 「foreach」ループを使用してコレクションを反復処理します。for (City city : from.getConnections())
  • 変数にクラス名と同じ名前を付ける傾向がありますが、小文字を使用するためcity、 , ではありませんtheCity
于 2011-09-26T10:25:06.710 に答える