Number Generator Function

Discussion in 'Resources' started by Monkeyboystein, Dec 16, 2013.

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

    Monkeyboystein

    I always looked for one and never found one, so heres one now!
    Code:java
    1. public int generateNumber(int min, int max)
    2. {
    3. Random r = new Random();
    4. int number = r.nextInt(max + 1 - min) + min;
    5. return number;
    6. }
    7.  

    Would be used like this:
    Code:
    int min = 0;
    int max = 100;
    int number = generateNumber(min, max);
    if(number == 52)
    {
    //DO CODE
    }
    Code:java
    1. if(generateNumber(1,10)==5)
    2. {
    3. //DO SOME MORE CODE HERE
    4. }

    Sorry for shortness, gotta run!
     
  2. Offline

    Quaro

    public int generateNumber
     
  3. Offline

    Not2EXceL

    Not to be rude, but a whole resource for a random nextint wrapper? Plus what Micius said. Its not void.
     
  4. Offline

    Monkeyboystein

    Yes, and thank you noticed that now, as i opened my laptop, first thing that caught my eye
     
  5. Offline

    Not2EXceL

    Monkeyboystein your example could also be if(randomInt(1, 10) == 5)
     
  6. Offline

    Monkeyboystein

    ill add another example thanks <3
     
  7. Offline

    TheE

    I would suggest reusing the random once it is created. Creating a new instance every time calling the method is not only unneeded, its also a waist of resources (creating new Randoms is quite a heavy task).
     
    bobacadodl likes this.
  8. Offline

    Conarnar

    Adding to this, Random has another constructor. new Random(long); What this does, is create a new Random object with the seed (the long). When new Random() called, it creates a new random from the system time. That means if multiple randoms are created at the exact same time, it will create the same exact numbers if the same methods are called.
     
    Phasesaber likes this.
Thread Status:
Not open for further replies.

Share This Page