Random Number 1/40 Chance

Discussion in 'Plugin Development' started by AstramG, Mar 10, 2013.

Thread Status:
Not open for further replies.
  1. Offline


    How could I make something occur on a 1 out of 40 chance, I'm using this for dropping mob heads at a 2.5% chance and I can't figure out how to make this happen at this 1/40 chance.
  2. AstramG
    Create a random number generator that goes to 39 (because it starts from 0)
    Then say:

    1. if ("that random number" == 1){
    2. //do something
    3. }
  3. Offline


    you could do a switch statement so it's not like if else if else if else if else if
  4. Code:
    Random r = new Random();
    int rand = r.nextInt(41);
    if (rand == 33) {
     Do stuff...
    Rand will be a number between 0-40 (0 and 40 included). You can take any number, I just did 33
  5. Offline


    Well, I understand the approach but I'm a bit confused on creating a random number generator, assistance in creating one would be nice :)

    Ah, thank you, but just for understanding why is nextInt 41? Why not 40?

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
    Last edited by a moderator: May 31, 2016

  6. He explained it already :)
  7. AstramG look at my post :D
    EDIT: nextInt will generate a number between 0 and arg-1. So nextInt(2) will give a number between 0 and 1 with 0 and 1 included
  8. No if you want a 1/40 chance, just use 39 there, because a number generator goes from 0 to <a choosen number>, 0 included, so use 39
  9. TomTheDeveloper molenzwiebel
    You're all wrong.
    You use randomGenerator.nextInt(40). That generates 40 numbers. It starts at 0, it ends at 39.
    So you don't use .nextInt(39), because it only gives 39 numbers, and you don't use .nextInt(41) either, because it gives 41 numbers.
    hapm likes this.
  10. Clean and simple way:
    int n = 1 + (int)(Math.random() * 40);
                if(n == 1){
    //Do Stuff >:D
  11. Rprrr
    Oh, sorry then, I was wrong, sorry

    Thx to correct me
Thread Status:
Not open for further replies.

Share This Page