Trying to figure this out for a while, need a random number that is either -1, 0 or 1. Any help would be great.
-
1Show your failed attempt here so we can advise how to fix it. – Marko Topolnik Oct 09 '16 at 10:36
-
4Take a look at [this](http://stackoverflow.com/questions/363681/generating-random-integers-in-a-specific-range/363732#363732) – asdf Oct 09 '16 at 10:37
5 Answers
Random random = ThreadLocalRandom.current();
int randomNumber = random.nextInt(3) - 1;
Will do the work

- 635
- 11
- 21
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:
- Cut the range:
max - min
- If you want to include upper bound value then will add 1:
nextInt((max - min) + 1)
(optional step) - 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();
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;

- 21
- 1
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.

- 6,548
- 8
- 42
- 69
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

- 1,568
- 16
- 30