In: Computer Science
Write a class called CombineTwoArraysAlternating that combines two lists by alternatingly taking elements, e.g. [a,b,c], [1,2,3] -> [a,1,b,2,c,3]. You must read the elements of the array from user input by reading them in a single line, separated by spaces, as shown in the examples below. Despite the name of the class you don't need to implement this class using arrays. If you find any other way of doing it, as long as it passes the test it is ok. HINTS: You don't need to use any of my hints. As long as you pass the test you can write the code any way you want. I used: String [] aa = line.split("\\s+"); to split the String contained in the variable called 'line' into strings separated by at least one white space character. For example if line is "hello world how are you?" the previous statement populates array aa in such a way that aa[0] is: "hello" aa[1] is: "world" aa[2] is: "how" aa[3] is: "are" aa[4] is: "you?" I used the method Arrays.toString from java.util.Arrays to print arrays. For example the following lines of code: String line = "hello world how are you?"; String [] aa = line.split("\\s+"); //Arrays.toString(aa) takes array aa and returns a nicely formatted String System.out.println(Arrays.toString(aa)); produce the following output: [hello, world, how, are, you?]
import java.util.Arrays; import java.util.Scanner; public class CombineTwoArraysAlternating { public static String[] combineAlternating(String[] aa, String[] bb) { String[] result = new String[aa.length+bb.length]; int index = 0; for (int i = 0; i < aa.length || i < bb.length; i++) { if (i < aa.length) { result[index++] = aa[i]; } if (i < bb.length) { result[index++] = bb[i]; } } return result; } public static void main(String[] args) { Scanner in = new Scanner(System.in); String line1 = in.nextLine(); String[] aa = line1.split("\\s+"); String line2 = in.nextLine(); String[] bb = line2.split("\\s+"); System.out.println(Arrays.toString(combineAlternating(aa, bb))); } }