Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random integers in a range [duplicate]

Tags:

java

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);
        }
    }

}
like image 493
Sozziko Avatar asked Dec 18 '25 07:12

Sozziko


1 Answers

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:

  • nextInt
like image 127
arshajii Avatar answered Dec 19 '25 21:12

arshajii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!