Random numbers in the non-zero range

I am trying to create a random number generator using java.util.Random. I need to generate numbers between -5 and +5, excluding zero. This is a bouncingbox app for one of my labs. A random number is the direction of field velocity.

Random v = new Random();
       int deltaX = -5 + v.nextInt(10)  ;
       for(; deltaX>0 && deltaX<0;){

           System.out.println(deltaX);
       }

I tried this, but this does not exclude zero. Any help would be appreciated.

+4
source share
8 answers

Here is one way:

int deltaX = -5 + v.nextInt(10);
if (deltaX >= 0) deltaX++;
+4
source

Another way:

int[] outcomeSet = {-5, -4, -3, -2, -1, 1, 2, 3, 4, 5};
int deltaX = outcomeSet[v.nextInt(10)];

If outcomeSetmade static, this should be the most efficient in terms of efficiency.

+4
source

:

public int getRandomWithExclusion(Random rnd, int start, int end, int... exclude) {
    int random = start + rnd.nextInt(end - start + 1 - exclude.length);
    for (int ex : exclude) {
        if (random < ex) {
            break;
        }
        random++;
    }
    return random;
}

:

int[] ex = { 2, 5, 6 };
val = getRandomWithExclusion(rnd, 1, 10, ex)

:

val = getRandomWithExclusion(rnd, 1, 10, 2, 5, 6)

(int) ( ) , exclude. . , : exclude , .

+3

, [-5,4], 0 , 1, [-5; -1] [1; 5].

, .

Random v = new Random();

boolean makeNegative = v.nextBoolean();
int value = v.nextInt(5) + 1; // range [1; 5]

if (makeNegative)
    value = -value;

, (boolean int), .

+2

: -

int deltaX = -5 + v.nextInt(10); 
if (deltax >= 0) deltax++;
+1
do {
  deltaX = -5 + v.nextInt(11);
} while (deltaX == 0)

The easiest way, still random (no +1).

+1
source

You can also do this:

Random random = new Random();
int random = random.nextInt(5) + 1;
int result = random.nextBoolean() ? random : -random;

Yes, it is less efficient because it requires two random values. The obtained intervals [-5 - 0) and [1 - 5]

+1
source

This is not the best way to solve this problem, but it will do it:

int deltaX = 0;
while(deltaX = 0) {
      deltaX = -5 + v.nextInt(10);
}
System.out.println(deltaX);
-1
source

All Articles