未输入任何内容且按下按钮时程序崩溃

问题描述 投票:0回答:1

你好,我正在制作一个随机数猜测游戏。问题是,如果用户没有输入任何数字并按下 if 条件中的按钮,则应执行 answerEmpty 变量,并且结果文本中应显示“请输入数字”。但是当我按下按钮时程序崩溃了。 else if 和 else 条件有效,但起始 if 条件无效。请帮忙

       class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //Calling button method
        val button = findViewById<Button>(R.id.guessBtn)
        //Set on click listener for the button
        button.setOnClickListener {
            buttonPressed()
           }
        }
       private fun buttonPressed() {
            //Method to find view from activity_main
            val result = findViewById<TextView>(R.id.result)
            val userAnsEditText = findViewById<EditText>(R.id.answer)
            val userAnsText = userAnsEditText.text.toString()
            val userAnsInt = userAnsText.toInt()
            //This variable will display the answer
            val answerCorrect = "Congrats, you have correctly guessed the number"
            val answerWrong = "Sorry,you have guessed the wrong number"
            val answerEmpty = "Please enter a number"
            //Making random numbers from 1 to 10
            val randomValues = Random.nextInt(1, 11)
            //Adding a condition to check if user answer matches the random answer
            if(userAnsInt == null){
                result.text = answerEmpty
            }
            else if(userAnsInt == randomValues){
                result.text = answerCorrect
            }
            else{
                result.text = answerWrong
            }

          }
android kotlin button crash
1个回答
0
投票

使用 Try catch 块, 例如

`

try {
    // Code that may cause an exception
    int result = 10 / 0; // This will throw an ArithmeticException
    Log.d("MyApp", "Result: " + result); // This line won't be executed
} catch (ArithmeticException e) {
    // Handle the exception
    Log.e("MyApp", "An arithmetic exception occurred: " + e.getMessage());
} 

` 以下是各部分的细分:

try: 可能引发异常的代码放置在此块中。 catch:如果try块中发生异常,则执行catch块。它指定要捕获的异常类型以及处理该异常的代码。 finally: 该块包含无论是否发生异常都将执行的代码。这是可选的。 之后您的应用程序将不会崩溃。它会显示错误,您可以在 Toast 或输出窗口中打印错误。

© www.soinside.com 2019 - 2024. All rights reserved.