我在网上找到了这个片段,它使用整数在 java 中创建了一个类似 array_intersect 的函数。
样本:
int[] intersect(int[] arr1, int[] arr2) {
int count = 0;
for(int a = 0; a < arr1.length; a++) {
for(int b = 0; b < arr2.length; b++) {
if(arr1[a] == arr2[b]) {
count++;
break;
}
}
}
int[] result = new int[count];
count = 0;
for(int a = 0; a < arr1.length; a++) {
for(int b = 0; b < arr2.length; b++) {
if(arr1[a] == arr2[b]) {
result[count++] = arr1[a];
break;
}
}
}
return result;
}
int[] arr1 = new int[] {10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
95, 85, 75, 65, 55, 45, 35, 25, 15, 05,
10, 15, 20, 25, 30, 35, 40, 45, 50, 55};
int[] arr2 = new int[] {15, 25, 35, 45, 55,
12, 22, 32, 43, 52,
15, 25, 35, 45, 55};
int[] p1 = this.unique(arr1);
int[] p2 = this.unique(arr2);
int[] intersectResults = this.intersect(arr1, arr2);
for(int a = 0; a < intersectResults.length; a++) {
System.out.print(intersectResults[a] + " ");
}
但是当我将其更改为:
String[] intersect(String[] a_yourname, String[] a_crushname) {
int count = 0;
for(int a = 0; a < a_yourname.length; a++) {
for(int b = 0; b < a_crushname.length; b++) {
if(a_yourname[a] == a_crushname[b]) {
count++;
break;
}
}
}
String[] result = new String[count];
count = 0;
for(int a = 0; a < a_yourname.length; a++) {
for(int b = 0; b < a_crushname.length; b++) {
if(a_yourname[a] == a_crushname[b]) {
result[count++] = a_yourname[a];
break;
}
}
}
return result;
}
String[] flames = this.intersect(a_yourname, a_crushname);
//String[] p23 = this.unique(arr2);
System.out.println("heheh" +flames.length);
for(int a = 0; a < flames.length; a++) {
System.out.print(flames[a] + " ");
}
有人可以向我解释我在这里做错了什么吗?我真的不熟悉Java。
a_yourname
并且a_crushname
都是字符串数组。