Trying to get a random string out of ListArray on the button pressed. Always getting the same, second element. No matter how big the array is.
Here’s what I have on key pressed:
int randIndex = getRandomIndex(ListArray.size());
String chosenItem = ListArray.get(randIndex);
Method getRandomIndex is claimed beforehand and looks like this:
public int getRandomIndex(int size) {
return (1+(int)Math.random()*size);
};
The cast from
inttodoublehas precedence over the multiplication bysize. When you castMath.random()to anint, the decimal is dropped and the result is0. Thus,getRandomIndexwill always return1.In other words,
is the same as
which is the same as
Fix it with:
This is more readable and ensures an even distribution of random numbers.