mercredi 28 octobre 2020

Java while loop random crashes [duplicate]

I have a code where I basically run through an array by custom order. I have included a code snippet of what goes wrong for me. For some reason Java sometimes gives me an arrayoutofboundsexception on 8, but to my knowledge the if statement in the while loop and before it should prevent it from reaching 8. Can someone explain to me what might be the cause of the variable val reaching 8 from time to time.

int size = 16;
done = new boolean[size/2];
int val = (int)(Math.random()*255);
int a = 0;
if ((size/2)<val)
  val=0;
while (done[val+a]) {
  a++;
  if ((val+a) > (int)(size/2)){
    val=0;
    a=0;
  }
}
done[val+a]=true;

Aucun commentaire:

Enregistrer un commentaire