英文:
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<String> = (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 ->
phrasesTextViews[index].text = phrase
}
But if you want all the phrases in a single String:
phrasesTextView.text = (1..10).map { it.toString() }.joinToString(", ")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论