Home > OS >  Kotlin - Dice roller app showing 2 dice - Shows only one
Kotlin - Dice roller app showing 2 dice - Shows only one

Time:08-21

I am taking the course "Android Basics in Kotlin". My task is to create 2 dice, which should be seen after clicking the Roll button. So when clicking the Roll button, 2 dice should be rolled and the results should be displayed in 2 different TextViews on screen.

This is the code I have come up with so far:

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()
        }
    }
}

My problem is that only the result of dice (not dice2) is displayed on screen. Could somebody please help me?

CodePudding user response:

Replace

resultTextView.text = diceRoll2.toString()

with

resultTextView2.text = diceRoll2.toString()

Because you set resultTextView.text twice.

CodePudding user response:

Thank you very much! It worked like a charm.Result

  • Related