'Compare two arrays and create a new array with only the same values from the first two
I need to the first two arrays to be inputted by the user so they can have different lengths and values and compare them and the similar elements should be written in a new third array I'm stuck at the writing of the third array can't seem to figure it out.
import java.util.Arrays;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("How many elements in the first array:");
int[] a = new int[console.nextInt()];
for (int i = 0 ; i < a.length ; i++){
System.out.println("Input element number: " + (i + 1) );
a[i] = console.nextInt();
}
System.out.println("How many elements in the second array: ");
int[] b = new int[console.nextInt()];
for (int i = 0; i < b.length; i++){
System.out.println("Input element number:" + (i + 1) );
b[i] = console.nextInt();
}
ArraySimilar(a,b);
}
public static void ArraySimilar(int[] a, int[] b) {
int[] c = new int[0];
for (int i = 0; i < a.length; i++) {
for (int j = i+1; i < b.length; i++) {
if (a[i] == b[j]) {
}
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|