How to add chance?

Discussion in 'Spigot Plugin Development' started by Cuulv, Jun 4, 2017.

  1. Is there a way so that I can make it so that, if a player dies, he has like a 20 percent chance of dropping something?
  2. Code (Text):
    Random random = new Random(); // Create a random
    int rand = random.nextInt(100) + 1; // creates a number between  1-100
    if(rand <= 20) {
    //Run code here
  3. You don't need necessarily a instance of Random. It would be fine to just use Math.random() to create a double value and then check for your chance.
    Code (Text):
    double chance = Math.random();
    If(chance <= 0.2){

  4. Mas


    Math.random() will return a decimal between 0.01 and 1.0, so you can compare the result of that method multiplied by 100 to the percentage chance you want. In this example you would check if Math.random() is less than or equal to 20.
  5. Creating a new instance of the random class every time you run some chances is not efficient. You should probably use ThreadLocalRandom.current() for that.

    Please use the search feature, there are hundreds of posts about this, but here's one:
  6. Could have had it at the top of your class? I agree, shouldn't have made a new instance.
  7. #7 Michel_0, Jun 4, 2017
    Last edited: Jun 4, 2017
  8. What would be better, out of curiousity? ThreadLocalRandom, new Random, or Math#random? I presume creating an instance of the random class would be inefficient, but I'm also wondering when that would ever be used over the other two options if this is the case?

    Sent from my iPhone using Tapatalk
  9. Mas


    If by "better" you mean speed, then ThreadLocalRandom.current().
    If you mean most secure, then SecureRandom, although it turns out to slower than the others.
    I'm assuming Math.random() just calls a random instance anyway.

    You can see a benchmark test comparing Random, SplittableRandom, SecureRandom and TLR conducted by @DarkSeraphim here.
  10. Thankyou :)

    Sent from my iPhone using Tapatalk