I read about Math.random()
(https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#random--)
and
Random
(https://docs.oracle.com/javase/8/docs/api/java/util/Random.html)
and I went through almost every post regarding generating random number on stack overflow,
and I still can't figure out how to generate a random number without a per-defined boundaries.
I mean, I know it's possible to write
Random random = new Random();
int mynumber = random.nextInt(max-min) + min;
but what if I don't want to supply these max
and min
? what if I want it to be also generated?
Bottom line, my purpose is to generate a random number, which can be also negative in the range of INT_MAX
and INT_MIN
.
I tried several ways:
int max = (int)Math.random();
int min = (int)Math.random();
double myNumber = new Random().nextInt(max - min) + min;
does not work because (int)Math.random()
always gets rounded to 0.
I also tried:
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
double myNumber = new Random().nextInt(max - min) + min;
and I get The call to 'nextInt' always fails as index is out of bounds
.
My purpose is to generate a random double
, but Random ().nextInt(x,y)
gets only int as x and y
. and to do that without supplying pre-defined values of max and min
.
How would you suggest me to do that? To generate a random and different double at each run of the program?
Thanks.
Aucun commentaire:
Enregistrer un commentaire