Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random numbers within a range excluding zero

Tags:

java

random

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.

like image 598
user2900748 Avatar asked Dec 02 '22 21:12

user2900748


2 Answers

Here is one way:

int deltaX = -5 + v.nextInt(10);
if (deltaX >= 0) deltaX++;
like image 101
user000001 Avatar answered Dec 16 '22 18:12

user000001


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.

like image 30
pjs Avatar answered Dec 16 '22 20:12

pjs