如何解决Kotlin - 掷 2 个骰子,每次都为两个骰子返回相同的值
我正在完成有关 android 开发人员中心的教程。挑战之一是将教程掷骰子扩展为包括 2 个骰子。我尝试创建我的骰子的第二个实例
var dice2 = Dice(6)
使用与我为我的第一个模具所做的相同的类定义。但是,两者都返回相同的值。所以我尝试为 Dice2 创建第二个类定义,并使用 `var dice2 = Dice2(6) 创建了一个实例。但我得到了同样的结果。以下是完整代码。
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val rollButton: Button = findViewById(R.id.button)
rollButton.setOnClickListener { rollDice() }
//roll the dice onLoad
rollDice()
}
private fun rollDice() {
//create two 6 sided die and rolls them
val dice = Dice(6)
val diceRoll = dice.roll()
val dice2 = Dice2(6)
val diceRoll2 = dice2.roll()
//assign the ImageViews called imageView and imageView2 to the variables diceImage and diceImage2
val diceImage: ImageView = findViewById(R.id.imageView)
val diceImage2: ImageView = findViewById(R.id.imageView2)
//update the die graphic based on the outcome of the dice roll
//assigns the resource id to a variable called drawableResource
val drawableResource = when(diceRoll) {
1 -> R.drawable.dice_1
2 -> R.drawable.dice_2
3 -> R.drawable.dice_3
4 -> R.drawable.dice_4
5 -> R.drawable.dice_5
else -> R.drawable.dice_6
}
/* do the same for the 2nd die */
val drawableResource2 = when(diceRoll2) {
1 -> R.drawable.dice_1
2 -> R.drawable.dice_2
3 -> R.drawable.dice_3
4 -> R.drawable.dice_4
5 -> R.drawable.dice_5
else -> R.drawable.dice_6
}
/*Update the die image source based on the variable
convert the die roll results from int to string and update the content description for
the die image
*/
diceImage.setImageResource(drawableResource)
diceImage.contentDescription = diceRoll.toString()
diceImage2.setImageResource(drawableResource)
diceImage2.contentDescription = diceRoll2.toString()
}
}
//create a class for an object called Dice & defines a roll function with random number
class Dice(private val numSides: Int) {
fun roll(): Int {
return (1..numSides).random()
}
}
class Dice2(private val numSides: Int) {
fun roll(): Int {
return (1..numSides).random()
}
}
非常感谢任何帮助。
解决方法
看来您在这一行中犯了一个错误:
diceImage2.setImageResource(drawableResource)
应该是:
diceImage2.setImageResource(drawableResource2)
,
尝试使用 diceImage2.setImageResource(drawableResource2)
而不是 diceImage2.setImageResource(drawableResource)
。但更好:
-
你绝对不需要
Dice2
;像原来一样使用val dice2 = Dice(6)
,甚至只是再次使用val diceRoll2 = dice.roll()
。 -
如果你做了一个函数,你甚至会避免犯那个错误的机会
fun showDiceResult(viewId: Int,rollResult: Int) { // get view by id // set image resource // set content description }
然后调用它两次
showDiceResult(R.id.imageView,diceRoll) showDiceResult(R.id.imageView2,diceRoll2)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。