什么类型的数组或列表应该用于完成我的随机化代码?

huangapple go评论82阅读模式
英文:

What kind of array or list should I use to complete my randomization code?

问题

button.setOnClickListener {
    //???
    val rand = Random().nextInt()
    phrase.text = rand.toString()
}

这是我目前的代码,但似乎找不到一个适合的数组,或者是listOf,它总是出现错误,代码有什么问题吗?我在这里的目标是在按钮点击后随机选择一些短语。

英文:
    button.setOnClickListener {
        //???
        val rand = Random().nextInt()
        phrase.text=rand.toString()}

This is my code so far, but I can't seem to find an array that fits, or listOf, it always seems to end up with an error, is there something wrong with the code? My goal here is to write a couple of phrases that will be chosen randomly once the button is clicked.

答案1

得分: 1

你可以使用listOf(),然后直接在列表上使用random(),无需创建随机整数:

val list = listOf("one", "two", "three", "four")
phrase.text = list.random()
英文:

You can use listOf(), and then use random() on the list directly, without the need to create a random int:

val list = listOf("one", "two", "three", "four")
phrase.text = list.random()

答案2

得分: 1

如果我正确理解您的问题,您可以像这样使用:

val random = Random(System.currentTimeMillis())
val list: List<String> = (1..10).map {
    random.toString()
}

// 现在您可以将字符串列表设置为任何您想要的内容
// 如果您有一个 TextView 数组...

list.forEachIndexed { index, phrase ->
    phrasesTextViews[index].text = phrase
}

但是,如果您希望将所有短语放在一个单独的字符串中:

phrasesTextView.text = (1..10).map { it.toString() }.joinToString(", ")
英文:

If I understood your question correctly, you could use something like that:

val random = Random(System.currentTimeMillis())
val list : List&lt;String&gt; = (1..10).map {
    random.toString()
}

// now you can set the list of strings to whatever you want
// if you have an array of TextViews...

list.forEachIndexed { index, phrase -&gt;
    phrasesTextViews[index].text = phrase
}

But if you want all the phrases in a single String:

phrasesTextView.text = (1..10).map { it.toString() }.joinToString(&quot;, &quot;)

huangapple
  • 本文由 发表于 2020年8月16日 01:13:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63428787.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定