java函数来检查和是偶数还是奇数,为什么我的代码不起作用?
我的代码有问题,没有导致任何错误,但没有给出结果 我编写了一个函数,用于检查数组中所有数字的和是偶数还是奇数:java函数来检查和是偶数还是奇数,为什么我的代码不起作用?,java,Java,我的代码有问题,没有导致任何错误,但没有给出结果 我编写了一个函数,用于检查数组中所有数字的和是偶数还是奇数: package tests; public class Test { public static String oddOrEven(int[] array) { int X = 0; String y; int i; for (i = 0; i <= array.length; i++) { X += array[i]; /
package tests;
public class Test {
public static String oddOrEven(int[] array) {
int X = 0;
String y;
int i;
for (i = 0; i <= array.length; i++) {
X += array[i]; // this is line 12
}
if (X % 2 == 0) {
y = "even";
} else {
y = "odd";
}
return y;
}
public static void main(String[] args) {
oddOrEven(new int[] {
4,
8,
9,
64,
21,
7
}); // this is line 25
}
}
我看到的例外情况是:
请帮忙
感谢您将您的声明更改为:
for (i = 0; i < array.length; i++) { //this line was wrong by you, use '<' instead of '<='
X += array[i];
}
您正在使用此运算符我发现索引有点问题,并添加了一些格式和输出:
public static String oddOrEven(int[] array) {
int X = 0;
String y;
int i;
//i needs to be smaller than the size as indexes start with 0(not with 1)
for (i = 0; i < array.length; i++) {
X += array[i];// this is line 12
}
if (X % 2 == 0) {
y = "even";
} else {
y = "odd";
}
return y;
}
public static void main(String[] args) {
String result = oddOrEven(new int[]{4, 8, 9, 64, 21, 7});// this is line 25
System.err.print(result);
}
将循环的条件更改为i