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

Java数组过滤器满足判定规则却返回0问题排查求助

问题原因分析

两个判定条件的内层循环逻辑均存在错误,导致最终结果不符合预期:

  • 条件1逻辑错误:找到元素9后遍历数组时,只要当前元素不等于11就将condition1设为false。哪怕数组中确实存在11,遍历到其他非11元素时condition1也会被覆盖为false,最终condition1的值仅由数组最后一个元素是否为11决定,你的测试数组最后一个元素为7,因此condition1被错误设为false。
  • 条件2逻辑错误:找到元素7后遍历数组时,只要当前元素不等于13就将condition2设为true。哪怕数组中确实存在13,遍历到其他非13元素时condition2也会被覆盖为true,最终condition2的值仅由数组最后一个元素是否为13决定。
  • 额外问题:原代码将condition1、condition2设为类成员变量,多次调用isFilter方法时会残留上次调用的判定结果,存在状态污染风险。

修复方案

正确的判定逻辑如下:

  1. 判定条件1时,找到元素9后先默认condition1为false,遍历数组只要找到11就将condition1设为true并终止遍历,未找到则保持false
  2. 判定条件2时,找到元素7后先默认condition2为true,遍历数组只要找到13就将condition2设为false并终止遍历,未找到则保持true
  3. 将condition1、condition2改为方法内部局部变量,每次调用重新初始化避免状态残留

修复后代码:

public class Question4 {
    private int [] array = {1,2,3,4,9,11,7};
    
    public int isFilter() {
        boolean condition1 = true;
        boolean condition2 = true;
        //condition 1 : 若数组中存在元素9,则必须同时存在元素11
        for (int i = 0; i < array.length; i++) {
            if (array[i] == 9) {
                condition1 = false;
                for (int j = 0; j < array.length; j++) {
                    if (array[j] == 11) {
                        condition1 = true;
                        break;
                    }
                }
                break;
            }
        }
        
        //condition 2 : 若数组中存在元素7,则数组中不能存在元素13
        for (int k = 0; k < array.length; k++) {
            if (array[k] == 7) {
                condition2 = true;
                for (int l = 0; l < array.length; l++) {
                    if (array[l] == 13) {
                        condition2 = false;
                        break;
                    }
                }
                break;
            }
        }
    
        //Evaluation and Return
        return condition1 && condition2 ? 1 : 0;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 09:09:03