我有两个这样的数组。
String[] arr1 = {"11","22","33","44","55","66","77"};
String[] arr2 = {"111","222","333","444","555","666","777","888","999"};
我想使用索引值的组合来合并这两个数组。
我的输入将是两个整数值(2:3 比率),如下所示
int firstArray = 2; //input value
int secondArray = 3; //input value
合并后,所有值将存储在单个列表中。现在我需要这样的输出。
11
22
111
222
333
33
44
444
555
666
55
66
777
888
999
77
下次执行此循环时,输入值应增加。
所以第二次调用for循环输入值(3:4比率)应该是这样的。
int firstArray = 3;
int secondArray = 4;
第二次输出:
11
22
33
111
222
333
444
44
55
66
555
666
777
888
77
999
我尝试使用 for 循环和循环链表。我无法为此执行适当的功能。任何人都可以提供构建适当功能的建议。
这是我尝试过的代码。
String[] arr1 = {"11","22","33","44","55","66","77"};
String[] arr2 = {"111","222","333","444","555","666","777","888","999"};
int f = 2;
for(int i=0;i<arr1.length;i++){
if(i == f){
f = f+f;
int s = 3;
for(int j=0;j<arr2.length ;j++){
if(j == s){
s = s+s;
}
if(j < s)
System.out.println(arr2[j]);
}
}
if(i < f)
System.out.println(arr1[i]);
}
提前谢谢。
你可以试试:
private static String[] mergeArrays(String[] arr1, String[] arr2, int firstArray, int secondArray) {
final String[] ret = new String[arr1.length + arr2.length];
for (int j = 0, k = 0; j < arr1.length || k < arr2.length;) {
while (j < arr1.length) {
ret[j + k] = arr1[j];
if (++j % firstArray == 0)
break;
}
while (k < arr2.length) {
ret[j + k] = arr2[k];
if (++k % secondArray == 0)
break;
}
}
return ret;
}
以下是如何称呼它:
public static void main(String[] args) {
String[] arr1 = { "11", "22", "33", "44", "55", "66", "77" };
String[] arr2 = { "111", "222", "333", "444", "555", "666", "777", "888", "999" };
String[] arr = mergeArrays(arr1, arr2, 2, 3);
System.out.println("Ratio 2:3");
for (String str : arr) {
System.out.println(str);
}
arr = mergeArrays(arr1, arr2, 3, 4);
System.out.println("Ratio 3:4");
for (String str : arr) {
System.out.println(str);
}
}