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);
}
}
}
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:
nextIntIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With