I have tried to solve this exercise for almost three hours now and I still don't understand what I am doing wrong. I am supposed to take two ArrayLists with numbers and merge them into one,but here's the catch, they must sorted like this:
If arraylist "A" has the numbers [1, 2, 3] and arraylist "B" has [9, 8, 7, 6, 5] then ArrayList "merge" should be [1, 9, 2, 8, 3, 7, 6, 5].
I.e it should alternate the numbers from the inputted arraylists A and B. If one arraylist is longer it should just keep on filling with numbers (like what happened to [7,6,5] in this case. Also, we don't know the length of any of the arrayLists.
Here's one solution that I think should work well, but I can't get it to work. All help is extremely appreciated!!
import java.util.ArrayList;
import java.util.Scanner;
public class test19 {
public static void main(String[] args) {
ArrayList<Integer> arrayListA = new ArrayList<>();
ArrayList<Integer> arrayListB = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("Write a number to place in ArrayList A, quit with '-1'");
int Local = sc.nextInt();
if(Local > 0) {
arrayListA.add(Local);
} else {
break;
}
}
System.out.println();
System.out.println();
while(true) {
System.out.println("Write a number to place in ArrayList B, quit with '-1'");
int Local = sc.nextInt();
if(Local > 0) {
arrayListB.add(Local);
} else {
break;
}
}
System.out.println(merge(arrayListB, arrayListA));
}
public static ArrayList<Integer> merge(ArrayList<Integer> a, ArrayList<Integer> b) {
ArrayList<Integer> merge = new ArrayList<>();
if(a.size() < b.size()) {
//here we check which list is the smallest and use that one (so we don't try to add blankspaces from the longer list to the merge list)
for(int i = 0; i <= a.size(); i++) {
merge.add(a.get(i));
merge.add(b.get(i));
}
for(int j = a.size(); j <= b.size(); j++) {
merge.add(b.get(j)); //here we add the leftover numbers to the list
}
} else { //this means that list A is bigger than list B
for(int i = 0; i <= b.size(); i++) {
merge.add(a.get(i));
merge.add(b.get(i));
}
for(int j = b.size(); j <= a.size(); j++) {
merge.add(b.get(j));
}
}
return merge;
}
}