简体   繁体   中英

How to generate random number to express the probability

I don't know how to make it in JAVA. Sorry everybody. My case is with 51% probability, I have to do something. and, with 49% probability, I don't have to do anything. I think I need to generate a random number, which will reference, express the probability.

how can I make it suitable to my case in Java? Thank you in advanced!

You can use the Random class. It has methods such as Random.nextInt where you can give it an upper bound and it will give you a random number between 0 (inclusive) and that number (exclusive). There are also other methods like Random.nextBoolean which returns 50% chance of true or false .

You can use Math.random function alternatively. The tutorial is here

Quoting javadoc.

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range. 

If you want to generate integer then you can use nextInt() method like this -

 Random randomGenerator = new Random();
 for (int i = 1; i <= 10; ++i){
   int randomInt = randomGenerator.nextInt(100);
   System.out.println("Generated : " + randomInt);
 }  

If you want double you can use nextDouble() method -

 Random randomGenerator = new Random();
 for (int i = 1; i <= 10; ++i){
   int randomInt = randomGenerator.nextDouble(100);
   System.out.println("Generated : " + randomInt);
 }  

And if you want to generate random between a range then you can do -

int shift=0;
int range=6;
Random ran = new Random();
int x = ran.nextInt(range) + shift;  

This code will generate random number (int) upto 6 (from 0 to 5). If you want to generate random number shifting the lower limit then you can change the shif value. For example changing the shift to 2 will give you all random number greater than or equal 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM