英文:
Find the intersection between using two array
问题
我编写了Java代码来找到两个数组之间的交集。
package CaseStudy;
public class Findintersection {
public static void main(String[] args) {
int[] series1 = {1, 2, 3, 4, 5};
int[] series2 = {3, 4, 5, 6, 7};
for (int i = 0; i < series1.length; i++) {
int x = series1[i];
System.out.println(x + " ");
}
for (int j = 0; j < series2.length; j++) {
int y = series2[j];
System.out.println(y + " ");
}
}
}
我使用for循环生成了各个值。但是我无法使用X和Y变量来比较数据。
我尝试使用IF条件来比较这些值。
if (x==y)
{
System.out.println(x + " ");
}
在比较过程中,要么X不可用,要么Y不可用。
英文:
I have written Java code to find the intersection between two arrays
package CaseStudy;
public class Findintersection {
public static void main(String[] args) {
int[] series1 = {1, 2, 3, 4, 5};
int[] series2 = {3, 4, 5, 6, 7};
for (int i = 0; i < series1.length; i++) {
int x = series1[i];
System.out.println(x + " ");
}
for (int j = 0; j < series2.length; j++) {
int y = series2[j];
System.out.println(y + " ");
}
}
}
I generated the individual values using for loop . But I am not able to use X and Y variable to compare the data.
I tried using IF conditions to compare the values.
if (x==y);
{
System.out.println(x + " ");
}
While comparing either X is not available or Y is not available.
答案1
得分: 3
你离答案很近了,你只需要将第二个for
循环嵌套在第一个循环内部,这样你就可以将第一个数组中的每个值与第二个数组中的每个值进行比较。
for (int i = 0; i < series1.length; i++) {
int x = series1[i];
for (int j = 0; j < series2.length; j++) {
int y = series2[j];
if(x == y)
System.out.format("%d : (%d, %d)%n", x, i, j);
}
}
输出结果:
3 : (2, 0)
4 : (3, 1)
5 : (4, 2)
英文:
You're close, you just need to nest the 2nd for
loop inside the 1st so that you compare each value in the 1st array with every value in the 2nd.
for (int i = 0; i < series1.length; i++) {
int x = series1[i];
for (int j = 0; j < series2.length; j++) {
int y = series2[j];
if(x == y)
System.out.format("%d : (%d, %d)%n", x, i, j);
}
}
Output:
3 : (2, 0)
4 : (3, 1)
5 : (4, 2)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论