radWin
radWin

Reputation:

Java Generate Random number {-1,0,1}

I need a function that will return a random integer that can be only -1, 0, or 1. Thanks?

Upvotes: 7

Views: 6510

Answers (3)

Bob Cross
Bob Cross

Reputation: 22292

This should help:

Random random = new Random();
int value = random.nextInt(3) - 1;

Upvotes: 5

Justin Ethier
Justin Ethier

Reputation: 134167

As Apocalisp wrote, you could do something like:

import java.util.Random;

Random generator = new Random();
int randomIndex = generator.nextInt( 3 ) - 1;

Upvotes: 18

Apocalisp
Apocalisp

Reputation: 35054

How about generating a random from 0 to 2 and subtracting 1?

Upvotes: 10

Related Questions