-2

Trying to figure this out for a while, need a random number that is either -1, 0 or 1. Any help would be great.

user3821904
  • 1
  • 1
  • 2

5 Answers5

0
Random random = ThreadLocalRandom.current();
int randomNumber = random.nextInt(3) - 1;

Will do the work

Dmitry Smorzhok
  • 635
  • 11
  • 21
0

If you use Java < 8 version then old approach will be great for you:

You can use java.util.Random class and its method nextInt(int bound). This method generates a random integer from 0 (inclusive) to bound (exclusive). If you want some specific range then you will need to perform some simple math operations:

  1. Cut the range: max - min
  2. If you want to include upper bound value then will add 1: nextInt((max - min) + 1) (optional step)
  3. Shift the generated number to the value of lower bound: nextInt((max - min) + 1) + min

Result:

Random r = new Random();
int randomNumber = r.nextInt((max - min) + 1) + min;

If you use Java >= 8 version, then there will be easier approach for you:

Now java.util.Random class provides other methods according to Stream api like:

public IntStream ints(int randomNumberOrigin, int randomNumberBound)
public IntStream ints(long streamSize, int randomNumberOrigin, int randomNumberBound)

Now you can generate a random integer from origin (inclusive) to bound (exclusive) like that:

Random r = new Random();
r.ints(min, max).findFirst().getAsInt();

If you want to include upper bound into generating process then:

r.ints(min, (max + 1)).findFirst().getAsInt();

To prevent producing unlimited stream:

r.ints(min, (max + 1)).limit(1).findFirst().getAsInt();

or

r.ints(1, min, (max + 1)).findFirst().getAsInt();

0

answer 1

long l = System.currentTimeMillis();
int randomNumber = (int) (l % 3) - 1;

answer 2

int randomNumber = (int) (Math.random() * 3) - 1;

answer 3

Random random = new Random();
int randomNumber = random.nextInt(3) - 1;
vansi
  • 21
  • 1
0

Look at this one

 Random r = new Random();

    int n = r.nextInt((1 - -1) + 1) + -1;
    System.out.println(n);

it will generate random between the range you want. output will be 1 or 0 or -1.

Inzimam Tariq IT
  • 6,548
  • 8
  • 42
  • 69
0

You can use int arrays with Random class. Store your values in an integer array, and generate random number for the index of the array.

Sample Code:

final int[] arr = new int[] { -1, 0, 1 };
Random number = new Random();
int n = number.nextInt(arr.length);
System.out.println(arr[n]); //arr[n] will give you random number
Amber Beriwal
  • 1,568
  • 16
  • 30