Kotlin 将文本编辑为整数

Kotlin Edit Text as Integer

我想制作一个应用程序,您必须在其中猜测两个等于随机数的数字。但是由于 java.lang.NumberFormatException,我的应用程序在开始时崩溃了:对于输入字符串:“”

val intNumber1 = etNumber1.text.toString().toInt() 是导致崩溃的行。但是我不知道怎么办。

这是我的主要内容 activity:

//Buttons und Text initialisieren
private lateinit var btnCheck: Button
private lateinit var tvRndNumber: TextView
private lateinit var etNumber1: EditText
private lateinit var etNumber2: EditText



override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)



    //Buttons und Text verknüpfen
    btnCheck = findViewById(R.id.checkButton)
    tvRndNumber = findViewById(R.id.randomNumber)
    etNumber1 = findViewById(R.id.inputNumber1)
    etNumber2 = findViewById(R.id.inputNumber2)



    val intNumber1 = etNumber1.text.toString().toInt()
    val intNumber2 = etNumber2.text.toString().toInt()



    fun getRandomNumber(): Int {
        return Random.nextInt(0,100)
    }



    var intRdnNumber = getRandomNumber()
    tvRndNumber.text = intRdnNumber.toString()



    fun checkNumbers(num1: Int, num2: Int){

        if (num1 + num2 == intRdnNumber) {
            tvRndNumber.text = "Richtig"
        }
        else {
            Toast.makeText(this,"Probier es nochmal", Toast.LENGTH_LONG).show()
        }
    }



    btnCheck.setOnClickListener {
        checkNumbers(intNumber1, intNumber2)
    }
 val intNumber1 = if(etNumber1.text.isNotEmpty()) {
       etNumber1.text.toString().toInt()
    } else {
       0
    }

     val intNumber2 = if(etNumber2.text.isNotEmpty()) {
        etNumber2.text.toString().toInt()
    } else {
        0
    }

像下面这样尝试

//....
 val intNumber1 = etNumber1.text.toString()
 val intNumber2 = etNumber2.text.toString()

//.....
btnCheck.setOnClickListener {
    if(intNumber1.isNotEmpty && intNumber2.isNotEmpty{
        checkNumbers(intNumber1.toInt(), intNumber2.toInt())
    }else{
        // input filed is empty
        // show message or do nothing
    }
    
}