0

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;
jeroen
  • 47
  • 1
  • 1
  • 7

1 Answers1

1

Check again. If val is exactly 8, your condition:

if ((size/2)<val)

Does not run, since 8!<8. Presumably you want:

if ((size/2)<=val)
code11
  • 1,986
  • 5
  • 29
  • 37
  • That seems to have done the trick but then my question becomes why does it work without problems on c++? – jeroen Oct 28 '20 at 14:01
  • Off the top of my head, perhaps C's Math.Random is exclusive, ie [0,1) while java's is inclusive [0,1]. Don't know for sure though. – code11 Oct 28 '20 at 14:03