一.使用Scala生成随机数
1.简单版本:
/*
1.you can use scala.util.Random.nextInt(10) to produce a number between 1 and 10
2.at the same time,you nextInt(100) to produce a number between 1 and 100
*/
object Test {
def main(args: Array[String]) {
var i = 0
while(i < 10)
var str = scala.util.Random.nextInt(100).toString
println(str)
i = i+1
}
}
}
2.复杂版本:
object Test{
def main(args: Array[String]): Unit = {
val wordPerMessage = 4
var i = 0
while(i<10){
/*
1.the (1 to 1) is meaning that only have one circulation.
*/
(1 to 1).foreach { messageNum => {
//[There's only three cycle]
val str: Seq[String] = (1 to wordPerMessage).map(x => scala.util.Random.nextInt(10).toString)
val str1 = str.mkString(" ")//separate str1 with space
println(str)
}
}
i = i +1
}
}
}
本文介绍如何使用Scala语言生成随机数,包括简单的随机数生成方法及更复杂的生成过程。通过两个实例,展示了如何生成指定范围内的随机整数,并提供了示例代码。
3160

被折叠的 条评论
为什么被折叠?



