Random.nextInt所在位置是kotlin.random.Random.nextInt,其相关用法介绍如下。

用法一

open fun nextInt(): Int
fun nextInt(): Int

从随机数生成器中获取下一个随机 Int

生成在 Int.MIN_VALUEInt.MAX_VALUE(含)之间均匀分布的 Int 随机值。

例子:

import kotlin.math.sin
import kotlin.random.Random
import kotlin.test.assertTrue

fun main(args: Array<String>) {
//sampleStart
val randomInts = List(5) { Random.nextInt() }
println(randomInts)
val sortedRandomInts = randomInts.sorted()
println(sortedRandomInts)
//sampleEnd
}

输出:

[-502126453, 107633748, 422047508, 667828383, -1468705199]
[-1468705199, -502126453, 107633748, 422047508, 667828383]

用法二

open fun nextInt(until: Int): Int
fun nextInt(until: Int): Int

从随机数生成器中获取小于指定 until 界限的下一个随机非负 Int

生成 Int 随机值均匀分布在 0(包括)和指定的 until 边界(不包括)之间。

例子:

import kotlin.math.sin
import kotlin.random.Random
import kotlin.test.assertTrue

fun main(args: Array<String>) {
//sampleStart
val menu = listOf("Omelette", "Porridge", "Cereal", "Chicken", "Pizza", "Pasta")
val forBreakfast = Random.nextInt(until = 3).let { menu[it] }
val forLunch = Random.nextInt(from = 3, until = 6).let { menu[it] }
// new meals every time
println("Today I want $forBreakfast for breakfast, and $forLunch for lunch.")
//sampleEnd
}

输出:

Today I want Cereal for breakfast, and Chicken for lunch.

参数

until- 必须是正的。

异常

IllegalArgumentException- 如果直到是负数或零。

用法三

open fun nextInt(from: Int, until: Int): Int
fun nextInt(from: Int, until: Int): Int

从指定范围内的随机数生成器中获取下一个随机Int

生成在指定的from(包括)和until(不包括)边界之间均匀分布的Int 随机值。

例子:

import kotlin.math.sin
import kotlin.random.Random
import kotlin.test.assertTrue

fun main(args: Array<String>) {
//sampleStart
val menu = listOf("Omelette", "Porridge", "Cereal", "Chicken", "Pizza", "Pasta")
val forBreakfast = Random.nextInt(until = 3).let { menu[it] }
val forLunch = Random.nextInt(from = 3, until = 6).let { menu[it] }
// new meals every time
println("Today I want $forBreakfast for breakfast, and $forLunch for lunch.")
//sampleEnd
}

输出:

Today I want Omelette for breakfast, and Pasta for lunch.

异常

IllegalArgumentException- 如果大于或等于直到.