How to get a random number???

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

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

    Armadillo

    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. Why should bukkit provide what Java provides? Just use the Random class.
     
  3. Offline

    gregthegeek

    Code:
    private static int getRandom(int min, int max) {
        return new java.util.Random().nextInt(max - min) + min;
    }
    
     
  4. 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. }
     
  5. Offline

    gregthegeek

    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. Then max is a bad variable name. ^^
     
  7. Offline

    gregthegeek

    max, exclusive.
     
  8. Offline

    Armadillo

Thread Status:
Not open for further replies.

Share This Page