Chances

Discussion in 'Spigot Plugin Development' started by harveycat1, May 28, 2017.

  1. How would i go about using random correctly as i need to make lots of percentages for things such as if a mob head drops (For every mob) then a 2nd percentage check for different mobs so it could be say a mob head has a 50% drop rate but then it might also have after that 20% for creeper 40% for zombie how would i set this up
     
  2. Code (Text):
    //101 since bound is exclusive and we want 0-100%
    if(ThreadLocalRandom.current().nextInt(101) <= chance) {
        ...
    }
     
  3. Code (Text):
        public static boolean percentRoll(int percent) {
            Random rand = new Random();
            return (rand.nextInt(100) < percent);
        }

     
    Spent 30s on google.
     
  4. Exactly! (Random#nextInt(int) will return a value between 0 (inclusive) and the parameter, int (exclusive) -> if the percent is 0, it will always return false (0 is not less than 0) and if percent is 100, it will always return true (nextInt will return max. 99))
    Except... Use ThreadLocalRandom instead (Creating a new Random class instance every time you need a random number is not efficient).
     
    • Agree Agree x 1
  5. i know that but some methods say to use <= etc
     
  6. You should comprehend any method you see , not just copy and paste .
     
    • Agree Agree x 2
  7. In that case, you will get false positives: if percent and nextInt(100) are both 0, the method would return true.
     
  8. Mas

    Mas

    Just a little tip, it's faster to use ThreadLocalRandom, and also keep once instance rather than creating a new one each time the method is called (applies to stuff other than random too).
     
  9. Using static method not as fast as this .
     
  10. Mas

    Mas

    What do you mean? Whether the method is static is nothing to do with that I said.
     
  11. ThreadLocalRandom.current() is a static method zz
     
  12. Using "ThreadLocalRandom.current" instead of "new Random" is a faster, more efficient solution.
     
    • Agree Agree x 1
  13. You could also just
    Code (Text):
    Random random = new Random();
    and then use the random instance.
     
  14. Mas

    Mas