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");
}
}