-2

I was making a code that makes some unique integers in a string and i suddenly ran into an exception and i don't quite get what is the problem here, because i was almost done. And now what is happening i don't know.

Here's my code:

String[] res = new String[12];
        int[] ia = {1, 6, 9};
        int[] ai = {97, 79, 8};
        int[] a = new int[10];
        for(int i = 0; i < a.length; i++){
            a[i] = (ia[new Random().nextInt(3)] ^ (ai[new Random().nextInt(3)] * i));
            for(int j = 0; j < res.length; j++){
                if(a[i] >= j){
                    res[j * i] = "J:" + (a[i] * a[new Random().nextInt(10)]); //exception
                } else if(a[i] <= j){
                    res[j * i] = "J:" + (-(a[i] * a[new Random().nextInt(10)]));
                }
            }
        } 

Here is the exception that is thrown:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12
    at testy.main(unique.java:15)
Matej Špilár
  • 2,617
  • 3
  • 15
  • 28
  • arrays are *zero based*. You're accessing the 13th element. Looking for one of the many dups of this. – Brian Roach Apr 28 '14 at 18:52
  • 3
    this code have so many errors that i cant even find a good line of code except the declarations of an arrays .... – Matej Špilár Apr 28 '14 at 18:54
  • What @MatejSpili said. For one thing, you should *not* be creating new `Random()` objects like that. You'll end up getting the exact same number numerous times. Create one at the start of your loop, and use the same one for everything there. – Andrew Barber Apr 28 '14 at 19:14

2 Answers2

0

Look at the maximum values of i and j. You will see that res[j * i] will exceed the space you have allocated for it and hence the out of bounds exception

attaboy182
  • 2,039
  • 3
  • 22
  • 28
0

In your first for you go from 0 to 9 (a.length = 10). In the second you go from 0 to 11 (res.length=12).

the j*i in res[j * i] will exceed the limit of res (12) with the simple values of 2 and 10.

pfernandom
  • 929
  • 10
  • 22