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

为何我的CalcOddIntegers方法始终返回0?

问题:统计数组中奇数个数时始终返回0的原因

我写了一个方法,接收用户输入的数组长度和元素,目的是统计数组里的奇数个数,但无论输入什么,结果始终是0。Scanner已经在方法外部声明了,代码如下:

System.out.print("Enter length of sequence\n");
int length = console.nextInt();
int[] array = new int[length];
System.out.print("Enter the sequence: \n");
int count = 0;
int i = 0;
for (i = 0; i < length; i++) {
    array[i] = console.nextInt();
}
for (i = 0; i < length -1; i++); {
    if (array[i] % 2 != 0) {
        count++;
    }
}
System.out.printf("The count of odd integers in the sequence is %d\n", count);
}

控制台运行示例:

2. Calculate the factorial of a given number
3. Calculate the amount of odd integers in a given sequence
4. Display the leftmost digit of a given number
5. Calculate the greatest common divisor of two given integers
6. Quit


3
Enter length of sequence
4
Enter the sequence: 
1
2
3
4
The count of odd integers in the sequence is 0

我试过更换for循环的变量来排查冲突,但没解决问题。


问题分析与修复

你的代码存在两个关键错误:

  1. 多余分号导致循环体为空
    第二个for循环末尾多了一个分号:for (i = 0; i < length -1; i++);,这个分号会让循环的执行体变成空语句,循环结束后才会执行后面大括号里的代码。此时i的值已经等于length-1(比如示例中length=4,循环结束后i=3),大括号里只会检查array[3]这一个元素,而示例里该元素是偶数4,所以count保持为0。

  2. 循环条件遗漏最后一个元素
    即便去掉分号,i < length -1的条件也会漏掉数组的最后一个元素,应该改成i < length才能遍历所有元素。

修正后的代码

System.out.print("Enter length of sequence\n");
int length = console.nextInt();
int[] array = new int[length];
System.out.print("Enter the sequence: \n");
int count = 0;
int i = 0;
for (i = 0; i < length; i++) {
    array[i] = console.nextInt();
}
// 去掉分号,修正循环条件
for (i = 0; i < length; i++) {
    if (array[i] % 2 != 0) {
        count++;
    }
}
System.out.printf("The count of odd integers in the sequence is %d\n", count);
}

修改后即可正确遍历数组所有元素并统计奇数个数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 08:20:22