The code returns 0 and the common numbers more than once. I want it to return an array with the common numbers once! So how do I return an array with numbers that are common to both arrays. I want to return {2,7,4} - something like this. I keep getting out of bounds exceptions when I try to return an array.
Thanks,
Barry
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));
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…