I am trying to do this problem but can't get around with it. Please tell me what i did wrong and any tips on how to solving it? Thanks.
here is the problem:
Write a method stutter that takes an ArrayList of Strings and an integer k as parameters and that replaces every string with k copies of that string. For example, if the list stores the values ["how", "are", "you?"] before the method is called and k is 4, it should store the values ["how", "how", "how", "how", "are", "are", "are", "are", "you?", "you?", "you?", "you?"] after the method finishes executing. If k is 0 or negative, the list should be empty after the call.
my code:
public static void stutter(ArrayList<String> list,int k) {
String s = "";
for(int i = 0; i<list.size(); i++) {
s = list.get(i);
}
for(int j = 0; j < k; j++) {
list.add(j,s);
}
}
-
Welcome to stackoverflow, you can try to improve the formatting of your code :)Paul Lo– Paul Lo2014年01月31日 05:39:13 +00:00Commented Jan 31, 2014 at 5:39
3 Answers 3
Well...two things are wrong here:
- You're not returning anything, which is a bit of a problem if you want to get back the modified list without changing/destroying your original data.
- Your loops aren't doing anything meaningful. The first loop is only going to give you the last element in your list, and then you only add that
ktimes. Most definitely not what you want.
I won't give the entire thing away, as this is an exercise for you, but here's some suggestions:
Create your own
ArrayList<String>to return instead of thatStringvariable. You'll also be declaring the method to returnArrayList<String>. May as well initialize it, too.Read each word in the list passed in. Add that to the local list
ktimes (hint: nested loops). If there's no words to be read, then the loop to add the elements isn't fired.
2 Comments
ConcurrentModificationException if you're not careful).Here is the code
public static List<String> stutter(ArrayList<String> list,int k) {
List<String> resultList=new ArrayList<String>(); // creating new list
if(k<=0) {
return resultList; //return empty list. Return null if necessary
} else {
for(String s : list) { //looping the list input
for(int i=0;i<k;i++) {
resultList.add(s); // adding the same string k times
}
}
return resultList;
}
}
Comments
- Second for loop should be nested in first for loop
- And strings should be added to a newlist instead of adding them to the samelist
Done modifications to your code.
public static void stutter(List<String> list,int k) {
String s = "";
List<String> newList=new ArrayList<String>();
if(k>0) {
for(int i = 0; i<list.size(); i++) {
s = list.get(i);
for(int j = 0; j < k; j++) {
newList.add(s);
}
}
}
list=newList; // Assigning it your input list since you want to change the actual list
System.out.println(list.toString()); //Since not returning anything, printing the data
}