Eventually occurs java.lang.ArrayIndexOutOfBoundsException [closed]

0

I made a simple algorithm for a book and there are two possible results. To test these results I have to run the program several times until Math.random () manages the possible numbers and displays the two possible results. The strange thing was that when I was running the code came a point where he presented a message

  

"Exception in thread" main "java.lang.ArrayIndexOutOfBoundsException: 3       at matrixReference3.Hobbits.main (Hobbits.java:25) "

But if I run the program again it returns a result. I would like to understand why this message appears, if it's something dangerous I'm doing in my code.

package matrizReferencia3;

public class Hobbits {
String name;

public static void main(String[] args) {

    Hobbits[] h = new Hobbits[3];
    int z = 0;
    int posicao = 5;

    while(z < 3){ 
        h[z] = new Hobbits();
        z++;
    }

    while (posicao > 3){
    posicao =(int) (Math.random() *10);
    }

    if (posicao == 2){
        h[posicao].name = "sam";
    }
    else{
        h[posicao].name = "frodo";
    }
    System.out.print(h[posicao].name + " is a ");
    System.out.println("good Hobbit name");
}
}
    
asked by anonymous 06.04.2015 / 14:43

1 answer

2

The error indicates that you are attempting to access an item from the h array whose index is greater than the size of that array.

The array was defined as having 3 items:

Hobbits[] h = new Hobbits[3];

The items will have the values 0 for the first, 1 for the second and 2 for the third. In the part of the code, where a random index is generated, the value 3 is allowed to be generated:

while (posicao > 3){
    posicao =(int) (Math.random() *10);
}

For this to happen, do not make the value greater than 2:

while (posicao > 2){
    posicao =(int) (Math.random() *10);
}
    
06.04.2015 / 14:57