Eventually java.lang.Arrayindexoutofboundsexception occurs

Asked

Viewed 227 times

0

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

"Exception in thread "main" java.lang.Arrayindexoutofboundsexception: 3 at matrizReferencia3.Hobbits.main(Hobbits.java:25)"

But if I run the program again it returns to present a result. I’d 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");
}
}
  • 1

    Your while (posicao > 3)should be while (posicao >= 3), because 3 is off the index (0 to 2). If it generates 3, it falls off the while and enters the else with 3 as index.

  • Why don’t you do posicao =(int) (Math.random() *2); to get numbers up to two, then avoid the while ?

  • Really, lack of attention my, thank you very much man!

  • Can’t this example be reproduced? Apparently Earendul and Ramaral succeeded, I vote to reopen.

  • "or is a typo"

1 answer

2


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

The array has been set to have 3 items:

Hobbits[] h = new Hobbits[3];

Items will have as index the values 0 for the first, 1 for the second and 2 for the third.
In the code part, where a random index is generated, it is allowed that the value 3 is generated:

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

So that this does not happen make the value is not greater than 2:

while (posicao > 2){
    posicao =(int) (Math.random() *10);
}
  • Thank you very much, much lack of attention on my part. It won’t happen again. Hugs!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.