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

Android应用复合控制语句运行异常:第二条件循环始终不执行

问题根因定位及修复方案

核心错误

你的代码中所有判断foundActive是否为假的条件语句,都错误使用了赋值运算符=,而非相等判断运算符==:

// 错误写法:这行是先给foundActive赋值为false,表达式结果永远为false,if块永远不会执行
if (foundActive = false)

这种写法的执行逻辑是:

  1. 先执行赋值操作,将foundActive强制设为false
  2. 取赋值后的值作为条件判断的依据,也就是永远用false判断,所以两个后续的if分支永远不会进入,和你预期的判断foundActive是否为假的逻辑完全不符。

修正后的代码

把两个if判断的运算符改成==即可:

private int getNextIndex() {
    int output = 0;
    Boolean foundActive = false;
    int size = lessonList.size();                                                               
    for (int i = 1; i <= (size - currentIndex - 1); i++) {
         if (lessonList.get(currentIndex + i).getActive()) {
             output = currentIndex + i;
             foundActive = true;                                                               
             break;
         }
    }
                                                                                       
    if (foundActive == false) {                                                                 
        for (int j = 0; j < currentIndex; j++) {
             if (lessonList.get(j).getActive()) {
                    output = j;
                    foundActive = true;
                    break;
             }
        }
    }                                                                                                    

    if (foundActive == false){
           output = currentIndex;
    }

    return output;
}

额外优化建议

  • 可以直接用!foundActive代替foundActive == false,写法更简洁,也能从根源上避免写错运算符的问题
  • 没有使用的局部变量relativeIndex可以删除,避免编译警告

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 01:00:05