我正在尝试交错两个数组,以便{1,2,3,4,5,6,7,8}。我怎么能这样做,我不断收到错误,说我的返回变量无法解析为类型。
package osu.cse1223;
public class Lab10b2 {
public static void main(String[] args) {
int [] array1= {1,3,5,7};
int [] array2= {2,4,5,8};
int n1=(array1.length)/(array2.length);
int n2=(array2.length)/(array1.length);
int [] array3=new int[n1+n2];
int [] result=mergearrays(array1,array2,n1,n2);
}
private static int[] mergearrays(int [] a1,int [] a2,int[] a3, int n1, int n2, int n3) {
int i=0;
int j=0;
int k=0;
while (i<n1&&j<n2) {
if(a1[i]<a2[j])
a3[k++]=a1[i++];
else
a3[k++]=a2[j++];
}
while (i<n1) {
a3[k++]=a1[i++];
}
while (j<n2) {
a3[k++]=a1[i++];
}
return a3[];
}
}
答案 0 :(得分:0)
据我所知,您不必返回a3,即array3,因为Java中的数组是引用。 如果您退货:请确保:
return a3;
不要
return a3[];
我不知道为什么你有n1,n2。 我的想法是
以下是我的代码。我希望它可以帮到你。
public class asdad {
public static void main(String[] args) {
int [] array1= {1,3,5,7};
int [] array2= {2,4,5,8};
/*Find how many numbers repeat in both arrays*/
int repeatedNumber=0;
for(int i=0;i<array1.length;i++) {
if(array1[i]==array2[i]) repeatedNumber++;
}
/*declare and assign a fix size for the array3*/
int [] array3=new int[array1.length+array2.length-repeatedNumber];
/*Call the function to do the job which is merge 2 arrays in asc order*/
mergearrays(array1,array2,array3);
/*Testing the array3*/
for(int i=0;i<array3.length;i++) {
System.out.println(array3[i]);
}
}
private static void mergearrays(int [] a1,int [] a2, int[]a3) {
int k=0;
for(int i=0;i<a1.length;i++) {
// Placing this condition first to ensure the repeating number will have one position in the a3
if(a1[i]==a2[i]) {
a3[k++]=a1[i];
}else {
if(i<a1.length) a3[k++]=a1[i];
if(i<a2.length) a3[k++]=a2[i];
}
}
}
}
结果是:
1
2
3
4
5
7
8