-1

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!

My Will
  • 400
  • 4
  • 27

3 Answers3

3

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.

gonzo
  • 2,103
  • 1
  • 15
  • 27
0

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. 
Tyagi Akhilesh
  • 744
  • 6
  • 15
0

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.

Razib
  • 10,965
  • 11
  • 53
  • 80