How would you give random limits in java?

后端 未结 3 1218
迷失自我
迷失自我 2021-01-24 13:34

So let\'s say you want to generate a random number, but you want it to be UNDER a specified amount. Is this possible?

相关标签:
3条回答
  • 2021-01-24 14:02

    The answers provided here are correct if you are looking for an integer. However, if you are not looking for an integer random number, I think the below solution would work.

    If you want a random number between 50 and 100, use this:

    randomNumber = 50+(Math.random()*50);

    0 讨论(0)
  • 2021-01-24 14:03
    Random rand = new Random();
    int randInt = rand.nextInt( 16 ); //Generates a number in [0, 1, .., 15]
    

    Documentation at: http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt(int)

    0 讨论(0)
  • 2021-01-24 14:03

    Use the following method random.nextInt(upperBound).

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