-
Arrayindex [resolved]
Does anyone know why this would happen?
When the first loop is excuted i get an ArrayIndexOutOfBounds
exception. But the second loopruns fine.
Code:
public class Test{
public static void main(String[] args){
String s = new String("ABC");
char[] c = new char[s.length()];
int[] intArray = new int[25];
for(int i = 0; i < s.length(); i++){
c[s.charAt(i)]++; // array index out of bounds
}
for(int k = 0 ;k < s.length(); ++k){
c[s.charAt(k)]++; // runs fine
}
}
}
-
char[] c = new char[s.length()];
is equivalent to
char[] c = new char[3];
which declares 3 chars that are addressible by indicies 0,1,2.
A=65
B=66
C=67
so the first loop is trying to address 3 chars at indices 65,66,67.
Since these indices do not exist in the char array named "c", these indices are out of bounds for this array.
The code as is doesn't survive past the first exception, so I don't see what you mean by the second loop working out. I'd suspect the same error since 65,66,67 are not in the range 0-24.
This may be related to you understanding the histogram code that counts integers.
-
What was i thinking :confused: Going from Access/Visual Basic
to Java scrambles my brain sometimes. :p