Click to See Complete Forum and Search --> : java.lang.ArrayIndexOutOfBoundsException


pnkflydgr
10-26-2010, 03:28 PM
I get this error about 1 out of three times I run the following code:else if (state == 7)
{
String license = "";
String[] chars = {"a","b","c","d","e","f","g","h","i","j","k","l","m",
"n","o","p","q","r","s","t","u","v","w","x","y","z","0","1",
"2","3","4","5","6","7","8","9"};

Random generator = new Random();
for (int x = 0; x < 26; x ++)
{
int digit = generator.nextInt(37);
license = license + chars[digit];
System.out.println(digit);
}
System.out.println(license);
}
}
catch (Exception e)
{
System.out.println(x);
e.printStackTrace();
} This is making me feel like a noob. Well. I am a noob. But it's making me feel noobier. My console is telling me the error is on the line 154 that contains: license = license + chars[digit];. I'll give you an example of the error code on my console: 15
16
6
23
3
32
24
7
java.lang.ArrayIndexOutOfBoundsException: 36
at Users.main(Users.java:154)
And it's always a random number that it errors after. Any ideas? This is what a successful run generates: ugahsw-bvpl-3gfvtq-a42s-z8e8a1

zimonyi
10-26-2010, 11:57 PM
Your array named chars has a length of 36 (26 letters and 10 numbers).

That means that your maximum index for the array is 35 (since arrays in Java start their index from zero).

Your random generator can generate numbers up to 36, which is why you get the ArrayIndexOutOfBounds when you randomly generate the value 36, since there is no such index in your array.

Archie

pnkflydgr
10-27-2010, 02:42 PM
Wow. Thanks man. Is there a way to remove posts so everybody doesn't know that I'm an idiot?

zimonyi
10-28-2010, 12:52 AM
He he. Well you do claim you're a noob so lets chalk it up to inexperience.

Archie