How to get a random number???

Discussion in 'Plugin Development' started by Armadillo, Sep 22, 2012.

  1. Offline

    Armadillo

    dev.bukkit.org profile:
    CFUSERNAME
    My Plugins (CFCOUNT)
    I have had the question for a while now. How can you get a random number between x and y. Would you use the java Random() class, or does bukkit have one.
    Any help is appreciated.
  2. Offline

    V10lator

    dev.bukkit.org profile:
    CFUSERNAME
    My Plugins (CFCOUNT)
    Why should bukkit provide what Java provides? Just use the Random class.
  3. Offline

    gregthegeek

    dev.bukkit.org profile:
    CFUSERNAME
    My Plugins (CFCOUNT)
    Code:
    private static int getRandom(int min, int max) {
        return new java.util.Random().nextInt(max - min) + min;
    }
    

    This post has been edited 1 time. It was last edited by gregthegeek Sep 22, 2012.
  4. Offline

    V10lator

    dev.bukkit.org profile:
    CFUSERNAME
    My Plugins (CFCOUNT)
    @gregthegeek Creating a new instance of Random is a heavy thing, so this would be better:
    Code:java
    1. private final Random rand = new Random();
    2.  
    3. private static int getRandom(int min, int max) {
    4. return rand.nextInt(max - min) + min;
    5. }
    6.  

    Other than that see the docu of nextInt: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Random.html#nextInt(int) - it will never give you the max value this way, so count max up:
    Code:java
    1. private static int getRandom(int min, int max) {
    2. return rand.nextInt(++max - min) + min;
    3. }

    This post has been edited 1 time. It was last edited by V10lator Sep 22, 2012.
  5. Offline

    gregthegeek

    dev.bukkit.org profile:
    CFUSERNAME
    My Plugins (CFCOUNT)
    That's assuming he wants that value in there. He may not. And yes, I would've done it your way as well, but my way was more compact.
  6. Offline

    V10lator

    dev.bukkit.org profile:
    CFUSERNAME
    My Plugins (CFCOUNT)
    Then max is a bad variable name. ^^
  7. Offline

    gregthegeek

    dev.bukkit.org profile:
    CFUSERNAME
    My Plugins (CFCOUNT)
    max, exclusive.
  8. Offline

    Armadillo

    dev.bukkit.org profile:
    CFUSERNAME
    My Plugins (CFCOUNT)

Share This Page