2015-11-13 33 views
1

你好,我创建了2个数组,我知道具有相同的类型int,并且可以具有相同的值,它们都是在特殊的间隔中随机创建的数字。数组比较不起作用,但为什么?

现在我想一个阵列的数量比较其他一个数,并有INT计数往往有多少在两个阵列相同的号码。

Array1 [1,5,7,8,11,15] 
Array2 [15,4,3,2,7,20] 

我希望计数器为2 Becasue有2场比赛15和7,但我的代码,我总是得到0。为什么呢?

for(int i= 0; i<t.length; i++){ 

    if(t[0]==zd[i]){ 
     counter = counter +1; 
    } else if(t[1]==zd[i]){ 
     counter = counter +1; 
    } else if(t[2]==zd[i]){ 
     counter = counter +1; 
    } else if(t[3]==zd[i]){ 
     counter = counter +1; 
    } else if(t[4]==zd[i]){ 
     counter = counter +1; 
    } else if(t[5]==zd[i]){ 
     counter = counter +1; 
    } 

    System.out.println(counter);  

} 

难道是因为我发起的计数器0以外的?

+2

你能告诉你的阵列是如何定义的? – dounyy

+0

你确定它们是'int []'而不是'Integer []'吗? –

回答

0

用户需要通过第二阵列使用嵌套循环循环。另外,你不需要所有那些如果陈述,一个会做:

int counter = 0; 

int [] t = {1,5,7,8,11,15}; 
int [] zd = {15,4,3,2,7,20}; 

for(int i= 0; i<t.length; i++){ 
    for(int j = 0; j < zd.length; j++) { 
     if(t[i]==zd[j]){ 
      counter++; // counter = counter + 1; 
     } 
    } 
} 
System.out.println(counter); 
1

使用嵌套循环。外部循环将遍历每个第一个数组值,并且对于每个第一个数组值,循环遍历所有第二个数组值。如果您找到匹配项,请增加计数器。

int [] arr1 = {1,5,7,8,11,15}; 
    int [] arr2 = {15,4,3,2,7,20}; 

    int matches = 0; 
    for(Integer arrayOneValue : arr1){ 
     for(Integer arrayTwoValue : arr2){ 
      if(arrayOneValue.equals(arrayTwoValue)){ 
       matches++; 
      } 
     } 
    } 

    System.out.println("Matches: " + matches); 
0
int counter = 0; 
for(int i = 0; i < t.length; i++) 
{ 
    for(int j = 0; i < zd.length, j++) 
    { 
    if(t[i] == zd[j]) counter++; 
    } 
} 
1

似乎有一些问题与您的阵列declaration.I尝试这样做,得到了预期的结果。

public class test { 
    public static void main(String a1[]) { 
     int[] t={1,5,7,8,11,15}; 
     int[] zd={15,4,3,2,7,20}; 
     int counter =0; 
     for(int i= 0; i<t.length; i++){ 



      if(t[0]==zd[i]){ 

        counter = counter +1; 
       }else if(t[1]==zd[i]){ 

        counter = counter +1; 
       }else if(t[2]==zd[i]){ 
        counter = counter +1; 
       }else if(t[3]==zd[i]){ 
        counter = counter +1; 
       }else if(t[4]==zd[i]){ 
        counter = counter +1; 
       }else if(t[5]==zd[i]){ 
        counter = counter +1; 
       } 

      } 
     System.out.println(counter); 

    } 
} 

输出

2 
0

如果阵列可以是类型的整数[],这可以很容易地使用CollectionUtils解决。

Integer[] array1 = {1,5,7,8,11,15}; 
    Integer[] array2 = {15,4,3,2,7,20}; 

    System.out.println(CollectionUtils.intersection(Arrays.asList(array1), Arrays.asList(array2)).size()); 
相关问题