You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android猜数字应用点击按钮崩溃问题求助

崩溃原因分析与修复方案

核心崩溃点

  • EditText内容获取错误:你通过findViewById<EditText>(R.id.answer).toString()拿到的是EditText控件的对象标识字符串(格式类似android.widget.EditText@xxxxxx),不是用户输入的文本。直接对这个字符串调用toInt()会触发NumberFormatException,导致程序崩溃。
  • 未处理非法输入:即使修正了内容获取逻辑,用户输入空值、非数字字符时,toInt()仍会抛出异常。
  • 随机数逻辑错误:每次点击按钮都重新生成随机数,导致用户的猜测永远无法和固定的目标数匹配,完全违背猜数字游戏的逻辑。

修复后的完整代码

class MainActivity : AppCompatActivity() {
    // 把随机数提升为成员变量,只初始化一次
    private lateinit var targetNumber: Int

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        // 初始化目标随机数(1-10,注意nextInt是左闭右开,所以写11才能包含10)
        targetNumber = Random.nextInt(1, 11)
        
        val button = findViewById<Button>(R.id.guessBtn)
        button.setOnClickListener {
            buttonPressed()
        }
    }

    private fun buttonPressed() {
        val resultTv = findViewById<TextView>(R.id.result)
        val answerEt = findViewById<EditText>(R.id.answer)
        
        // 1. 获取用户输入并做非空/格式校验
        val userInput = answerEt.text.toString().trim()
        if (userInput.isEmpty()) {
            resultTv.text = "请输入一个数字"
            return
        }
        
        val userAns = try {
            userInput.toInt()
        } catch (e: NumberFormatException) {
            resultTv.text = "请输入有效的整数"
            return
        }

        // 2. 校验输入范围(可选,符合游戏规则)
        if (userAns !in 1..10) {
            resultTv.text = "请输入1-10之间的数字"
            return
        }

        // 3. 对比用户输入和固定的目标数
        val answerCorrect = "Congrats, you have correctly guessed the number"
        val answerWrong = "Sorry,you have guessed the wrong number"
        resultTv.text = if (userAns == targetNumber) answerCorrect else answerWrong
    }
}

关键修改说明

  • 将随机数targetNumber改为Activity成员变量,在onCreate中初始化一次,确保游戏过程中目标数固定。
  • 用answerEt.text.toString()正确获取用户输入的文本,而非控件本身的toString结果。
  • 添加了非空校验和格式异常捕获,避免非法输入导致崩溃。
  • 补充了输入范围校验(可选),引导用户输入符合规则的数字。
  • 修正了随机数生成范围:Random.nextInt(1,11)才能生成1到10的整数(原代码nextInt(1,10)只能生成1-9)。

内容的提问来源于stack exchange,提问作者Blinky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 17:17:26