0

I've just started programming and was trying to make a randomizer where a random number will be generated and that random number will be linked with a name which will then show up, and I can't figure out the problem in my code, this is the error that pops up

"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
    at random.Randomiser.main(Randomiser.java:21)" 

package random;

public class Randomiser {

    public static void main(String[] args) {

        int number = ((int) (Math.random()*10))+1;

        int[] intArray = new int[9];

        intArray[0] = 1;
        intArray[1] = 2;
        intArray[2] = 3;
        intArray[3] = 4;
        intArray[4] = 5;
        intArray[5] = 6;
        intArray[6] = 7;
        intArray[7] = 8;
        intArray[8] = 9;
        intArray[9] = 10;

        if (number == 1) 
            System.out.println("Isaac");
        if (number == 2) 
            System.out.println("Madgeline");
        if (number == 3) 
            System.out.println("Cain");
        if (number == 4) 
            System.out.println("Judas");
        if (number == 5) 
            System.out.println("Blue Baby");
        if (number == 6) 
            System.out.println("Eve");
        if (number == 7) 
            System.out.println("Samson");
        if (number == 8) 
            System.out.println("Azazel");
        if (number == 9) 
            System.out.println("Lazarus");
        if (number == 10) 
            System.out.println("Eden");
    }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
JackC
  • 13
  • 1
  • The javascript tag has been removed as your question appears to have nothing to do with this language. Please be careful with tag use, since proper use can get the right experts to your question, but also the converse is true. – Hovercraft Full Of Eels Aug 12 '15 at 23:04
  • protip: to init your array, use a for loop; like `for(int i=0; i < intArray.length; i++){ intArray[i] = i+1; }` – blurfus Aug 12 '15 at 23:06

3 Answers3

0

Change array size. Now your size is 9 and max index is 8:

int[] intArray = new int[10];
ka4eli
  • 5,294
  • 3
  • 23
  • 43
0

You have indexes from 0 to 8 here. You don't have 9th index. int[] intArray = new int[9]; Change it to int[] intArray = new int[10] or remove intArray[9] = 10;

And you can declare your array like this int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

Bukk94
  • 419
  • 1
  • 6
  • 23
0

You must create the array like this:

int[] intArray = new int[10]; 

When you create an array you give the size:

int[] intArray = new int[9];  // size is 9

When you access to it you start in position 0, so when you do:

intArray[9] = 10; 
// you're accessing to a non created position of the array 
// max position is intArray[8] then:
// IndexOutOfBounds exception is thrown.
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109