Error out of bounds exception when running recursive program in Java
I'm learning about recursion as part of a Java tutorial and I am looking for a little help.
We need to make a recursive Java program which will work out how to get from one city to the other when there is no direct flight.
My latest issue is Im getting an error out of bounds exception after the code has 2 cities in the flightRoute array List. it gives the error开发者_JAVA技巧 "IndexOutOfBoundsException Index 2 Size 2"
The connection value is an arrayList which takes all the cities that the city connects with and the flightRoute is also an arrayList which keeps track of the cities we have had to travel to in order to reach our destination.
I just cannot work out why it will not proceed.
I would appreciate some help on this if you could.
I do not want to overflow you guys with code so i'll put up the method that you should need. If you need more I will happily add some more code.
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;
}
Where do you set the i
value? Anyway, the only get()
you do use i
as index, so it is clear that Connections
does not have as much items as i
.
BTW:
a) Next time mark at which line the exception is thrown (from what I see, probaly the first get()
b) use lowercase for variable names: connections
instead of Connections
The problem is that i
is non declared locally, so you're forever incrementing some instance variable. Declare it locally and set it to zero.
Before you can make any real progress fixing this code, I advise you clean it up:
- Name variables with a leading lowercase - ie
connections
notConnections
- Use local variables where it makes sense - like
connections
- Remove nonsense code, such as the test if
7 > 8
is true - of course it's always true! - Use proper indentation of blocks
- Iterate over collections using a "foreach" loop:
for (City city : from.getConnections())
- Tend to name your variables the same as the class name, but with a lowercase letter, so
city
, nottheCity
精彩评论