阵列比较不起作用,但为什么?

时间:2015-11-13 14:56:42

标签: java arrays compare

你好我创建了2个数组,我知道它们具有相同的int类型,并且可以具有相同的值,两者都包含在特殊的intervall中随机创建的数字。

现在我想将一个数组的数字与另一个数组的数字进行比较,并且有一个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);    

}

可能是因为我在for?

之外启动了0的计数器

5 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

您的阵列声明似乎存在一些问题。我尝试了这个并得到了预期的结果。

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

答案 2 :(得分:0)

您需要使用嵌套循环来遍历第二个数组。另外,你不需要所有那些if语句,一个会做:

.mfsForm {
    padding-left: 90px;
    position: absolute;
    left: 100px;
    top: 250px;
    font-family:"Bubblegum Sans";
    font-size: 22px;
    text-decoration: none;
    color: #FFF;
    text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000;
    margin: auto;
    width: 400px;
    height: 200px;
    overflow: auto;
     border: 2px solid red;
}

.content { border: 2px solid green;
}

答案 3 :(得分: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++;
  }
}

答案 4 :(得分:0)

如果数组的类型为Integer [],则可以使用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());
相关问题