我正在做一个作业,我需要创建两个数组,然后查看它们并创建一个新数组来保存前两个数组中的任何值。最初,我接近通过创建一个数组列表来完成此任务,但我的实验室教授告诉我这是不允许的,所以我需要重新开始并且没有足够的时间来找出解决方案。
如果您想查看我现在拥有的完整代码:http://pastebin.com/thsYnj2z
我真的很挣扎在这里的这个循环:
for(int i = 0 ; i < Xarr.length ; i++){
for(int j = 0 ; j < Yarr.length ; j++)
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
k++;
System.out.println(ArrA[k]);
break;
}
我的 ArrA[k] 数组的输出仍为 0。我似乎无法独自解决这个问题。
最佳答案
尝试进行这些更改
for(int i = 0 ; i < Xarr.length ; i++){
for(int j = 0 ; j < Yarr.length ; j++)
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
System.out.println(ArrA[k]); // or print them all later
k++;
break; // break to outer loop
}
}
}
注意
假设 OP 已正确初始化 ArrA
注释2
假设只需要唯一值,因此会破坏
关于java - 从一个数组中获取数据来创建另一个数组。这个循环有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39261582/