Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在两个数组中查找匹配数_Java_Arrays_Oop - Fatal编程技术网

Java 在两个数组中查找匹配数

Java 在两个数组中查找匹配数,java,arrays,oop,Java,Arrays,Oop,嘿,我正在尝试编写一个方法来比较两个数组,并返回它们共有的值的数量 例如,如果有两个阵列: arr{0,4,2,5} arr1{0,7,4,4} 然后该方法将返回2 这就是我到目前为止所做的: public int numDigitsCorrect(Permutation other) { int c=0; for(int i=0; i<nums.length; i++) { for(int x=0; x<nums.length;x++) {

嘿,我正在尝试编写一个方法来比较两个数组,并返回它们共有的值的数量

例如,如果有两个阵列:

arr{0,4,2,5} 
arr1{0,7,4,4}
然后该方法将返回2

这就是我到目前为止所做的:

public int numDigitsCorrect(Permutation other) {
    int c=0;
    for(int i=0; i<nums.length; i++) {
        for(int x=0; x<nums.length;x++) {
            if(nums[i]==other.nums[x]) {
                System.out.println(nums[i] + " " + other.nums[x] + " ");               
                c++;
            }
        }
    }
    return c;
}
public int numDigitsCorrect(置换其他){
int c=0;
对于(inti=0;i,如果您使用,它将更加清晰易读。这也将降低代码的复杂性

比如:


您需要更改当前功能,如下所述:

public int numDigitsCorrect(Permutation other)  
{
    int c=0;
    for(int i=0; i<nums.length; i++) {
        for(int x=0; x<other.length;x++) {
           if(nums[i]==other[x]) {
               System.out.println(nums[i] + " " + other[x] + " ");               
               c++;
           }
       }
   }
   return c;
}

你运行代码了吗?你得到了什么错误?在第二个循环中,现在输出的xAs是3。在
c++;
之后添加
break;
,这将在第二个数组中停止4次计数,那么输出将变为2。你可以引入
Set
来提高代码的复杂度。@Niroshan,如果我们反转输入,那么再加一次。@Niroshann输出将为3。
2
2
4
3
public int numDigitsCorrect(Permutation other)  
{
    int c=0;
    for(int i=0; i<nums.length; i++) {
        for(int x=0; x<other.length;x++) {
           if(nums[i]==other[x]) {
               System.out.println(nums[i] + " " + other[x] + " ");               
               c++;
           }
       }
   }
   return c;
}
int[] nums = {0,4,2,5}; 
int[] other = {0,7,4,4};