2

Possible Duplicate:
Generating random number in a range with Java

This feels pretty silly, but I'm not sure how to create a random integer, giving it a specific range to allow. I was trying to make it generate random numbers between -1 and 1. I tried doing that, but the nextInt part doesn't allow two parameters to be put within the parentheses. Am I supposed to be using something different?

import java.util.Random;

public class Testttterrrr {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Random rng = new Random();
        for (int i=0;i < 10; i++)
        {
        int pepe = 0;
        pepe = rng.nextInt(1, 1-2);
        System.out.println(pepe);
        }
    }

}
Community
  • 1
  • 1
Sozziko
  • 129
  • 1
  • 3
  • 10

4 Answers4

6

You could do

pepe = rng.nextInt(3) - 1;

rng.nextInt(3) returns a random element in the set {0, 1, 2} - therefore subtracting 1 returns a random element in the set {-1, 0, 1}, as desired.


Relevant documentation:

arshajii
  • 127,459
  • 24
  • 238
  • 287
4

Try this statement: int pepe = rng.nextInt(3) - 1;

Juvanis
  • 25,802
  • 5
  • 69
  • 87
4

Use

pepe = rng.nextInt(3) - 1;

To return random sequences of -1, 0, 1.

rng.nextInt(3)

returns a random number in the interval [0..2]. Subtract 1 and you get the interval [-1..1].

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
3
pepe = rng.nextInt(3) - 1;

the random number will be either 0, 1, or 2. then subtracting 1 will give you either -1, 0, or 1 just like you want

Kailua Bum
  • 1,368
  • 7
  • 25
  • 40