0

kotlin 生成指定范围的随机数

josephine created at6 years ago view count: 6456
import java.util.Random

object Rand {
    @JvmStatic fun main(args: Array<String>) {
        print(randInt(1, 1000000000))
    }

    /**
     * Returns a pseudo-random number between min and max, inclusive.
     * The difference between min and max can be at most
     * `Integer.MAX_VALUE - 1`.

     * @param min Minimum value
     * *
     * @param max Maximum value.  Must be greater than min.
     * *
     * @return Integer between min and max, inclusive.
     * *
     */
    fun randInt(min: Int, max: Int): Int {

        // NOTE: Usually this should be a field rather than a method
        // variable so that it is not re-seeded every call.
        val rand = Random()

        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        val randomNum = rand.nextInt((max - min) + 1) + min

        return randomNum
    }
}
report
回复

Recent search keywords