I'm just learning java and working on a homework problem. Our assignment was two read two-word lists into arrays and then combine them into one ArrayList alternating the words in the list. e.g. L1[0], L2[0], L1[1], L2[1], etc.
I've got my code almost running EXCEPT if the word lists are not exactly the same length, I either leave off the last words in the long list or get an out-of-bounds index for the shorter list. I know there must be an obvious solution I haven't thought of. Thanks for your help!
Here is the code I've written:
public class ArrayMixer {
public static void main (String[] args){
Scanner scnr= new Scanner(System.in); // set up scanner
// Initialize variables to capture user inputs
String firstLine;
String secondLine;
//collect user input for the first list
System.out.println("Please enter the first word list:"); // prompt user for first list
firstLine= scnr.nextLine();
String[] firstArray= firstLine.split(" "); // creates array to store first line split by spaces
//System.out.println(firstLine);//FIXME COMMENT OUT AFTER TESTING
//System.out.println(Arrays.toString(firstArray));//FIXME COMMENT OUT AFTER TESTING
//collect user input for the second list
System.out.println("Please enter the second word list:");// prompt user for second list
secondLine= scnr.nextLine();//
String[] secArray= secondLine.split(" ");//create array to store second list split by spaces
//System.out.println(secondLine);//FIXME COMMENT OUT
//System.out.println(Arrays.toString(secArray)); //FIXME COMMENT OUT
//Create an array list called mixList to store combination of list 1 and 2
ArrayList <String> mixList = new ArrayList<String>();
// need to find out size of two lists put together
int mixSize= (firstArray.length + secArray.length);
System.out.println(mixSize);
//HERE IS MY PROBLEM I've replace secArray.length w/ mxSize, and firstArray.length NO DICE
for (int i=0; i< secArray.length; ++i) {//FIXME NEED TO FIGURE OUT HOW TO GET THE LOOP
// NOT GO OUT OF BOUNDS
mixList.add(firstArray[i]);
mixList.add(secArray[i]);
}
//print new list to output
for (int i=0; i< mixList.size(); ++i) {
String tempWord=mixList.get(i);
System.out.println(tempWord);
}
}
}
I've tried using the length of the two lists combined and the length of the longer list-> index out of bounds, the shorter list- last words of the longer list left off because the loop never gets to their index.
Is there some sort of special arrayList for loop I can use?
Here is one way to combine them. You will need to adapt this to your specific requirements.
And here is another.
both print