代码返回0,并且不止一次返回公共数字。我希望它返回一个数组,并且有一次共同的数字!那么,如何返回数组以及两个数组通用的数字。我想返回{2,7,4} - 就像这样。当我尝试返回一个数组时,我总是跳出界限异常。 谢谢, 巴里在两个整数数组中找到公共元素java
public class Test {
public int findCommonElement(int[] a, int[] b){
int counter=0;
int temp= 0;
int tempCounter = 0;
for(int i=0; i<a.length; i++){
temp=a[i];
tempCounter=0;
for(int j=0; j<b.length; j++){
if (temp==b[j]){
tempCounter++;
}
}
if (tempCounter == 1) {
temp = a[i];
counter++;
System.out.println(temp);
}
}
return 0;
}
public static void main(String []args){
int myArray[] = {2,2,7,7,2,1,5,4,5,1,1};
int myArray2[] = {2,3,4,7,10};
Test hello = new Test();
System.out.println(hello.findCommonElement(myArray, myArray2));
}
}
它因为你的方法被设置为返回这里0 – darkhouse
多个问题返回0。首先,你的函数返回0.第二,如果你想返回多个数字,你必须改变findCommonElement以返回一个数组或列表。 – mdewit
另外,findCommonElement中的计数器变量当前不执行任何操作。为什么if(tempCounter == 1)语句只检查tempCounter是否为1?不应该如果(tempCounter> 0)? – mdewit