Final answer:
To find the elements that only appear in one of the arrays, iterate through each element in one array and check if it exists in the other array. If not, add it to a new array. Finally, return the new array as the result.
Step-by-step explanation:
To solve this problem, you can iterate through each element in one array and check if it exists in the other array. If an element is not found, add it to a new array that will store the elements that only appear in one of the arrays. Finally, return the new array as the result.
- Create an empty ArrayList to store the elements that only appear in one of the arrays.
- Iterate through each element in the first array.
- Check if the element exists in the second array using the contains() method.
- If the element does not exist in the second array, add it to the new ArrayList.
- Repeat steps 2-4 for the second array.
- Convert the ArrayList to an array using the toArray() method and return it as the result.
Here's the code implementation for the 'problem9' method:
import java.util.ArrayList;
public class MyClass {
public static int[] problem9(int[] array1, int[] array2) {
ArrayList<Integer> result = new ArrayList<>();
for (int num : array1) {
if (!contains(array2, num)) {
result.add(num);
}
}
for (int num : array2) {
if (!contains(array1, num)) {
result.add(num);
}
}
return result.toArray(new int[result.size()]);
}
private static boolean contains(int[] array, int target) {
for (int num : array) {
if (num == target) {
return true;
}
}
return false;
}
}