【问题标题】:Cannot create an instance of an abstract class Random kotlin无法创建抽象类随机 kotlin 的实例
【发布时间】:2019-11-23 01:41:07
【问题描述】:

我试图在 Android Studio 上制作一个 Dice Roller 应用程序,但是当我输入这个 Random() 时,我收到一个错误,说“无法创建抽象类的实例”请帮助我

package com.example.diceroller

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val rollbutton: Button = findViewById(R.id.roll_button)
        rollbutton.setOnClickListener(
            View.OnClickListener { diceRoll() }


        )
    }
    private fun diceRoll() {
        val resultText: TextView = findViewById(R.id.result_text)
        val randomInt = Random().nextInt(6) + 1
        resultText.text = randomInt.toString()
    }
}

我希望每当我点击按钮时输出在 6 到 1 之间是随机的

【问题讨论】:

标签: java android random kotlin


【解决方案1】:

Kotlin 中的 Random 是抽象的,但它提供了一些可以直接使用的静态方法,如下所示:

Random.nextInt(6)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    相关资源
    最近更新 更多