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

Android Studio中含循环的check()函数致程序崩溃问题解决

修复循环版check()函数的问题

问题根源

  1. 索引越界崩溃:原代码直接访问secondPlayer[0]/[1]/[2]和firstPlayer[0]/[1]/[2],但游戏初期玩家步数不足3步时,会触发IndexOutOfBoundsException,直接导致程序闪退。
  2. 重复触发提示:找到获胜组合后未终止循环,会重复执行加分和Toast提示。
  3. 平局逻辑错误:即使已有玩家获胜,平局提示仍会弹出。

修复方案

// 先修正集合声明,确保类型安全(原firstPlayer未指定泛型)
var firstPlayer = ArrayList<Int>()
var secondPlayer = ArrayList<Int>()
private val wincombination = listOf(
    listOf(1,2,3), listOf(4,5,6), listOf(7,8,9),
    listOf(1,4,7), listOf(2,5,8), listOf(3,6,9),
    listOf(1,5,9), listOf(3,5,7)
)

private fun check() {
    var hasWinner = false

    // 检查第二个玩家是否获胜(先判断步数≥3,避免索引越界)
    if (secondPlayer.size >= 3) {
        for (combination in wincombination) {
            // 用集合子集判断替代硬编码索引,更安全简洁
            if (combination.all { it in secondPlayer }) {
                score.add(1, 1)
                Toast.makeText(this, "0 is winner", Toast.LENGTH_SHORT).show()
                hasWinner = true
                break // 找到获胜组合后立即终止循环
            }
        }
    }

    // 第二个玩家未获胜时,再检查第一个玩家
    if (!hasWinner && firstPlayer.size >= 3) {
        for (combination in wincombination) {
            if (combination.all { it in firstPlayer }) {
                score.add(0, 1)
                Toast.makeText(this, "X is winner", Toast.LENGTH_SHORT).show()
                hasWinner = true
                break
            }
        }
    }

    // 无获胜者时再判断平局
    if (!hasWinner && firstPlayer.size + secondPlayer.size == 9) {
        Toast.makeText(this, "it's draw", Toast.LENGTH_SHORT).show()
    }
}

关键优化点

  • 增加步数判断:只有玩家已选数字≥3个时,才执行获胜检查,彻底避免索引越界。
  • 用combination.all { it in playerList }替代逐个索引访问,逻辑更清晰且安全。
  • 加入hasWinner标记:找到获胜者后终止后续检查,避免重复操作,同时确保平局逻辑仅在无获胜者时触发。
  • 修正firstPlayer的泛型声明,避免类型不安全问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 03:10:56