I'm trying to create a Random number generator using, java.util.Random
. I need to generate numbers between -5 and +5 excluding zero. This is for bouncingbox app for one of my labs. The random number is the direction of the velocity of the box.
Random v = new Random();
int deltaX = -5 + v.nextInt(10) ;
for(; deltaX>0 && deltaX<0;){
System.out.println(deltaX);
}
I've tried this, but it doesn't exclude zero. Any help would be appreciated.
Here is one way:
int deltaX = -5 + v.nextInt(10);
if (deltaX >= 0) deltaX++;
Yet another way:
int[] outcomeSet = {-5, -4, -3, -2, -1, 1, 2, 3, 4, 5};
int deltaX = outcomeSet[v.nextInt(10)];
If the outcomeSet
is made static this should be the most computationally efficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With