搜索两个数组

时间:2015-12-01 08:16:18

标签: java arrays

我是一名Java新手,需要Arrays的帮助。

我现在有两个阵列。

int [] array1 = {2,5,7};
int [] array2 = {3,5,9};

我必须找到两个数组之间的第一个匹配元素,显然是5.显然首先我们将查看array1中的元素,然后查找这些元素以查看它们是否也在array2中。我很确定我必须使用循环,只是不确定哪些以及如何编码。任何帮助,将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:0)

我认为这可能会对你有所帮助

for(int index1=0;index1<array1.length();index1++)
 {
 for(int index2=0;index2<array2.length();index2++)
  {
   if(array1[index1]==array2[index2])
   {
    System.out.println(array1[index1]+" is present in both array.");
   }

  }
}

答案 1 :(得分:0)

您可以尝试类似以下的内容

如果您只是在数组中寻找公共元素,那么在任何索引处:

    //Loop through array1
    for (int inArray1 : array1) {
        //For each element in array1, loop through array2
        for (int inArray2 : array2) {
            //If they are equal, we have found a common element
            if (inArray1 == inArray2) {
                System.out.println("First common element: " + inArray1);
                break; //We've found it, no need to keep going
            }
        }
    }

如果您希望匹配元素位于公共索引处:

    //In-case the arrays have a different length
    int commonLength = Math.min(array1.length, array2.length);
    //For each element in BOTH of the arrays
    for(int index = 0; index < commonLength; index++) {
        //If the corresponding elements are equal, we have found our common
        if(array1[index] == array2[index]) {
            System.out.println("First matching element: " + array1[index] + " at index " + index);
            break; //We've found it, no need to keep going
        }
    }