Stackoverflow.
I'm trying to add 4 of each words in my ArrayList into the ArrayList itself. I have in my ArrayList two Strings. One is "java" and the other one is "Program". I'm trying to write a program that adds a total of 4 words of each word. Ex: I'm trying to add 4 x java and 4 x program.
Here's what I've got so far. I have no idea, what I'm doing wrong. Any help or hints would be much appreciated.
/*
* Write a method called quadList that takes an ArrayList of strings as a parameter
* and replaces every string with four of that same string.
* For example, if the list stores the values ["java", "program"]
* before the method is called,it should store the values
* ["java ", " java ", " java ", " java ", "program", "program", "program", "program"]
* after the method finishes executing.
*/
import java.util.ArrayList;
public class Ex10_4_quadList {
public static void main(String[] args) {
ArrayList<String> arrList = new ArrayList<String>();
arrList.add("Java");
arrList.add("Program");
System.out.println("Before: " + arrList);
quadList(arrList);
System.out.println("after " + arrList);
}
private static void quadList(ArrayList<String> list) {
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < 4; j++) {
String temp = list.get(i);
list.add(temp);
}
}
}
}
Here's the fixed code:
public class Ex10_4_quadList {
public static void main(String[] args) {
ArrayList<String> arrList = new ArrayList<String>();
arrList.add("Java");
arrList.add("Program");
System.out.println("Before: " + arrList);
quadList(arrList);
Collections.sort(arrList);
System.out.println("after " + arrList);
}
private static void quadList(ArrayList<String> list) {
int initial = list.size();
for (int i = 0; i < initial; i++) {
for (int j = 0; j < 3; j++) {
String temp = list.get(i);
list.add(temp);
}
}
}
}
i < list.size(). Since you are adding items to the list in the loop, it will change across the iterations. What you might want to consider doing isint initial = list.size();before the loop and change the checking condition to 'i < initial'. However if you want those to be sequential, you would need to use a different addadd(int index, E element)