Possible Duplicate:
How to generate random positive and negative numbers in java
Hello I am trying to create a method in Java to create negative and positive values in Java.
the problem is that I don't know how to get this programmed but I do know the logic.. here is what I tought it should be
Random generator = new Random();
for (int i = 0; i < 21; i++)
{
System.out.print(generator.nextInt(100) + 1);
System.out.println();
}
but with the code above I get only positive values and I need values between -100 and 100 but how can I accomplish something like that?
The correct code is int rand = new Random(). nextInt((30 - 20) + 1) + 20; .
One of the tricky parts of this question is that Java has multiple data types to support numbers like byte, short, char, int, long, float, and double, out of those all are signed except char, which can not represent negative numbers.
The nextDouble() and nextFloat() method generates random value between 0.0 and 1.0. The nextInt(int bound) method accepts a parameter bound (upper) that must be positive. It generates a random number in the range 0 to bound-1.
You can use:
Random generator = new Random();
int val = 100 - generator.nextInt(201);
Or, as JoachimSauer suggested in the comments:
int val = generator.nextInt(201) - 100;
The general formula is
int val = rand.nextInt(max - min + 1) + min;
Note that min
and max
can be negative. (max > min)
If 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