I am trying to generate random integers over the range (-32768, 32767) of the primitive data type short. The java Random object only generates positive numbers. How would I go about randomly creating numbers on that interval? Thanks.
The correct code is int rand = new Random(). nextInt((30 - 20) + 1) + 20; .
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.
In order to generate Random double type numbers in Java, we use the nextDouble() method of the java. util. Random class. This returns the next random double value between 0.0 (inclusive) and 1.0 (exclusive) from the random generator sequence.
Random random = new Random(); int rand15Digt = random. nextInt(15);
You random on (0, 32767+32768)
then subtract by 32768
Random random=new Random();
int randomNumber=(random.nextInt(65536)-32768);
public static int generatRandomPositiveNegitiveValue(int max , int min) {
//Random rand = new Random();
int ii = -min + (int) (Math.random() * ((max - (-min)) + 1));
return ii;
}
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