为什么这段代码不起作用? 我应该编写一个函数,从数组中删除奇数。这是我的代码,但我不知道哪里出错了。它给我一个错误。
public class Test{
public static int [] removeOdd(int[] input){
int c = 0;
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
c++;
}
}
int [] a = new int[c];
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
a[i] = input[i];
}
}
return a;
}
public static void main(String [] args){
int [] mixedArray = {21, 33, 44, 66, 11, 1, 88, 45, 10, 9};
for (int i = 0; i < mixedArray.length; i++) {
System.out.print(mixedArray[i] + " ");
}
System.out.println();
int [] noOdd = Test.removeOdd(mixedArray);
for (int i = 0; i < noOdd.length; i++) {
System.out.print(noOdd[i] + " ");
}
}
提前致谢:)
最佳答案
您需要另一个索引变量来访问 a
的项目并且不使用 i
:
public static int [] removeOdd(int[] input){
int c = 0;
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
c++;
}
}
int [] a = new int[c];
int k = 0;
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
a[k] = input[i];
k++;
}
}
return a;
}
索引变量i
遍历input
,它的值不匹配,会超过a
索引的允许值,所以我使用过k
。
关于Java从混合数组中删除奇数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54792705/