【发布时间】:2018-11-17 14:19:07
【问题描述】:
我需要创建一个数组,其值出现在两个给定数组中。
我正在考虑循环遍历每个数组并比较值,如果它们匹配,则增加一个“计数器”变量,该变量将是新数组的长度,循环遍历新数组并将值分配给数组元素。
我需要找出一个循环的解决方案,下面的代码是我目前所得到的
class New {
public static void main(String[] args) {
int arr1[] = {2, 4, 5, 7, 9, 10};
int arr2[] = {1, 2, 5, 6, 8};
int counter = 0;
int combined[] = new int[counter];
for (int s = 0; s < arr1.length; s++) {
for (int x = 0; x < arr2.length; x++) {
for (int i = 0; i < combined.length; i++) {
if (arr1[s] == arr2[x]) {
counter++;
combined[i] = arr1[s];
}
}
}
for (int i = 0; i < combined.length; i++) {
System.out.print(combined[i] + " ");
}
}
}
}
【问题讨论】:
-
那么您面临的问题是什么?
-
I need to figure out a solution with a loop你的意思是没有循环? -
你需要计数器做什么?
-
我不能在没有数组大小的情况下在 Java 中声明一个数组,这就是我创建计数器变量的原因,以计算有多少匹配值将是数组的大小问题与这段代码是它不会在控制台中打印任何内容,最后一个循环应该打印出数组的变量
-
@Julia 我现在看到了。是的,您正在创建大小为 0 的数组。
int combined[] = new int[counter];当您增加计数器时,此数组不会自行调整大小。而且我认为combined[i] = arr1[s];无论如何都会抛出异常。老实说,代码还有其他几个问题。
标签: java arrays algorithm loops for-loop