Hi there,
I have some code that does various simple things to some ArrayLists that I have created.
However, I get an out of bounds exception on the line i hightlight below
I have spent what must be an hour trying to solve what must be a simple problem!
For reference: distances is a 2Darray of type string with size of intSize(Currently 12) (A print of for it is below)
|
Code:
|
/**
*
* @author grahambthreeonefouratgmaildotcom
* @version 1.0
* Traveling Salesman Java Project
* Start: 03/Nov/08
*
*/
//ERROR: Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 11, Size: 11
ArrayList cities = new ArrayList<Integer>();
System.out.println();
int d=1;
//Populate the arrayList with all cities) eg 1-12 where intSize=12
for(int i=0; i<intSize; i++) {
cities.add(d);
d++;
//print Arraylist to test
//System.out.println(cities.get(d-2)+ " ");
}
System.out.println();
System.out.println();
while (cities.size() != 0) { //while not null (ATM it will always be null till finished)
int x=0;
Integer currentCity = ( Integer ) cities.get(x);
cities.remove(x);
int i=0;
ArrayList tempCities = new ArrayList<Integer>();
//get distances from this city to the rest into the Temp array list
for (i=0; i<distances.length;i++)
{
int u = distances[currentCity-1][i];
//int u = distances[5-1][i];
tempCities.add(i,u);
//print for testing
//System.out.println(tempCities.get(i)+ " ");
}
System.out.println();
//find smallest city in the temp array
i = 0;
int smallest = 999999999;
for (i = 0; i<tempCities.size(); i++ ) {
if (( Integer ) cities.get(i) == 0) { //ERROR IS ON THIS LINE
i++;
}
Integer curr = ( Integer ) cities.get(i);
if ( curr < smallest) {
smallest = curr;
System.out.println(smallest + " ");
}
} |
distances array print out (not an arraylist)
0 53 6 8 20 40 15 7 30 29 2 3
53 0 30 35 50 5 6 10 12 20 30 32
6 30 0 4 10 15 15 9 9 9 8 3
8 35 4 0 7 21 14 13 12 11 17 8
20 50 10 7 0 30 32 34 20 6 40 25
40 5 15 21 30 0 9 14 7 13 31 32
15 6 15 14 32 9 0 4 21 25 15 16
7 10 9 13 34 14 4 0 31 35 4 10
30 12 9 12 20 7 21 31 0 5 50 40
29 20 9 11 6 13 25 35 5 0 27 21
2 30 8 17 40 31 15 4 50 27 0 5
3 32 3 8 25 32 16 10 40 21 5 0
Thanks!