how can i use random numbers in groovy?

前端 未结 5 1011
野性不改
野性不改 2020-12-13 17:49

I use this method:

def getRandomNumber(int num){
    Random random = new Random()
    return random.getRandomDigits(num)
}

when I call it I

相关标签:
5条回答
  • 2020-12-13 18:19

    For example, let's say that you want to create a random number between 50 and 60, you can use one of the following methods.

    new Random().nextInt()%6 +55
    

    new Random().nextInt()%6 returns a value between -5 and 5. and when you add it to 55 you can get values between 50 and 60

    Second method:

    Math.abs(new Random().nextInt()%11) +50
    

    Math.abs(new Random().nextInt()%11) creates a value between 0 and 10. Later you can add 50 which in the will give you a value between 50 and 60

    0 讨论(0)
  • 2020-12-13 18:22

    Generally, I find RandomUtils (from Apache commons lang) an easier way to generate random numbers than java.util.Random

    0 讨论(0)
  • 2020-12-13 18:30

    If you want to generate random numbers in range including '0' , use the following while 'max' is the maximum number in the range.

    Random rand = new Random()
    random_num = rand.nextInt(max+1)
    
    0 讨论(0)
  • 2020-12-13 18:32

    There is no such method as java.util.Random.getRandomDigits.

    To get a random number use nextInt:

    return random.nextInt(10 ** num)
    

    Also you should create the random object once when your application starts:

    Random random = new Random()
    

    You should not create a new random object every time you want a new random number. Doing this destroys the randomness.

    0 讨论(0)
  • 2020-12-13 18:37

    Generate pseudo random numbers between 1 and an [UPPER_LIMIT]

    You can use the following to generate a number between 1 and an upper limit.

    Math.abs(new Random().nextInt() % [UPPER_LIMIT]) + 1

    Here is a specific example:

    Example - Generate pseudo random numbers in the range 1 to 600:

    Math.abs(new Random().nextInt() % 600) + 1
    

    This will generate a random number within a range for you. In this case 1-600. You can change the value 600 to anything you need in the range of integers.


    Generate pseudo random numbers between a [LOWER_LIMIT] and an [UPPER_LIMIT]

    If you want to use a lower bound that is not equal to 1 then you can use the following formula.

    Math.abs(new Random().nextInt() % ([UPPER_LIMIT] - [LOWER_LIMIT])) + [LOWER_LIMIT]

    Here is a specific example:

    Example - Generate pseudo random numbers in the range of 40 to 99:

    Math.abs( new Random().nextInt() % (99 - 40) ) + 40
    

    This will generate a random number within a range of 40 and 99.

    0 讨论(0)
提交回复
热议问题