我的問題很簡單。我有以下幾點:
enum Colors:
case Blue, Red, Green
如何從此列舉中選擇一個隨機元素?我嘗試了這個問題的解決方案,但沒有用。
uj5u.com熱心網友回復:
您可以使用Random.nextInt生成隨機列舉值的索引。
這避免了Array對值的混洗,并且只生成一個亂數。
import scala.util.Random
enum Colors:
case Blue, Red, Green
object Colors:
private final val colors = Colors.values
def random: Colors = colors(Random.nextInt(colors.size))
@main def run: Unit =
println(Colors.random)
uj5u.com熱心網友回復:
enum Colors:
case Blue, Red, Green
@main def run: Unit =
import scala.util.Random
val mycolor = Colors.values
println(Random.shuffle(mycolor).head)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/368226.html
