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");
}
}
Your
while (posicao > 3)
should bewhile (posicao >= 3)
, because 3 is off the index (0 to 2). If it generates 3, it falls off thewhile
and enters theelse
with 3 as index.– Franchesco
Why don’t you do
posicao =(int) (Math.random() *2);
to get numbers up to two, then avoid thewhile
?– Franchesco
Really, lack of attention my, thank you very much man!
– Filipi Maciel
Can’t this example be reproduced? Apparently Earendul and Ramaral succeeded, I vote to reopen.
– Guilherme Nascimento
"or is a typo"
– ptkato