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

Java数组奇偶判断代码输出异常,请求排查错误

问题排查:Java判断数组全奇数逻辑错误

需求说明

给定t个测试用例,每个测试用例包含长度为n的数组:

  • 若数组存在偶数元素,输出NO
  • 若所有元素均为奇数,输出YES

当前问题

运行代码后,第一个测试用例输出NO符合预期,但第二个本该输出YES的测试用例也输出NO,与预期结果不符。

输入示例

2
5
1 2 5 4 3
1
7

实际输出

NO
NO

预期输出

NO
YES

我的代码

import java.util.Scanner;

public class dsj {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        while (t-- > 0){
            int n = sc.nextInt();
            boolean k = true;
            for (int i = 0; i < n; i++) {
                int x = sc.nextInt();
                if (x % 2 == 0) {
                    k = false;
                    break;
                }
            }
            if (k)
                System.out.println("YES");
            else
                System.out.println("NO");
                
        }
        sc.close();
    }
}

错误原因分析

问题出在第一个测试用例提前break后,未读取完该测试用例的剩余元素,导致后续输入读取错位:
第一个测试用例中,当读到第二个元素2(偶数)时,设置k=false并break循环,但此时该测试用例还剩3个元素(5、4、3)未被读取。这些残留的输入会被第二个测试用例的读取逻辑错误捕获:

  • 第二个测试用例首先读取5作为n的值,而不是预期的1
  • 接着尝试读取n=5个元素,但后续输入只有4、3、1、7,实际读取到的元素包含偶数,最终错误输出NO

修复方案

方案1:不提前终止循环,读完所有元素

即使发现偶数元素,也继续读完当前测试用例的全部元素,避免输入指针错位:

import java.util.Scanner;

public class dsj {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        while (t-- > 0){
            int n = sc.nextInt();
            boolean k = true;
            for (int i = 0; i < n; i++) {
                int x = sc.nextInt();
                if (x % 2 == 0) {
                    k = false;
                    // 不提前break,继续读完剩余元素
                }
            }
            System.out.println(k ? "YES" : "NO");
        }
        sc.close();
    }
}

方案2:提前终止循环,但跳过剩余元素

如果想提前终止循环以优化效率,可以在设置k=false后,手动跳过当前测试用例的剩余元素:

import java.util.Scanner;

public class dsj {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        while (t-- > 0){
            int n = sc.nextInt();
            boolean k = true;
            for (int i = 0; i < n; i++) {
                int x = sc.nextInt();
                if (x % 2 == 0) {
                    k = false;
                    // 跳过当前测试用例的剩余n-i-1个元素
                    for (int j = i+1; j < n; j++) {
                        sc.nextInt();
                    }
                    break;
                }
            }
            System.out.println(k ? "YES" : "NO");
        }
        sc.close();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 07:45:59