Kotlin-骰子滚动应用程序显示2个骰子-只显示一个



我正在参加课程"Kotlin的Android基础";。我的任务是创建2个骰子,点击滚动按钮后可以看到。因此,当点击滚动按钮时,应该滚动2个骰子,结果应该显示在屏幕上的2个不同的文本视图中。

这是我迄今为止想出的代码:

package com.example.diceroller
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
/**
* This activity allows the user to roll a dice and view the result
* on the screen.
*/
class MainActivity : AppCompatActivity() {
/**
* This method is called when the Activity is created.
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Find the Button in the layout
val rollButton: Button = findViewById(R.id.button)

// Set a click listener on the button to roll the dice when the user taps the button
rollButton.setOnClickListener { rollDice() }
}
/**
* Roll the dice and update the screen with the result.
*/
private fun rollDice() {
// Create new Dice object with 6 sides and roll it
val dice = Dice(6)
val diceRoll = dice.roll()
val dice2 = Dice.Dice2(6)
val diceRoll2 = dice2.roll2()

// Update the screen with the dice roll
val resultTextView: TextView = findViewById(R.id.textView)
resultTextView.text = diceRoll.toString()
val resultTextView2: TextView = findViewById(R.id.textView2)
resultTextView.text = diceRoll2.toString()
}

}
/**
* Dice with a fixed number of sides.
*/
class Dice(private val numSides: Int) {
/**
* Do a random dice roll and return the result.
*/
fun roll(): Int {
return (1..numSides).random()
}
class Dice2(private val numSides: Int) {
/**
* Do a random dice roll and return the result.
*/
fun roll2(): Int {
return (1..numSides).random()
}
}
}

我的问题是屏幕上只显示骰子的结果(而不是骰子2(。有人能帮帮我吗?

更换

resultTextView.text=diceRoll2.toString((

使用

resultTextView2.text=diceRoll2.toString((

因为您设置了两次resultTextView.text。

最新更新