below programs give the correct output in intellij but it shows some error in codegym check.. could you please help what is the error?
package com.codegym.task.task07.task0716;
import java.util.ArrayList;
/*
R or L
*/
public class Solution {
public static void main(String[] args) throws Exception {
ArrayList<String> list = new ArrayList<String>();
list.add("rose"); // 0
list.add("love"); // 1
list.add("lyre"); // 2
list.add("measure");
list.add("wade");
list.add("bark");
list = fix(list);
for (String s : list) {
System.out.println(s);
}
}
public static ArrayList<String> fix(ArrayList<String> list) {
for(int i=0;i<list.size();i++) {
if (list.get(i).contains("r") && !(list.get(i).contains("l"))){
list.remove(i);
}
}
int a = list.size();
for(int i=0;i<a;i++){
if (list.get(i).contains("l") && !(list.get(i).contains("r"))){
list.add(list.get(i));
i++;
}
}
return list;
}
}
what is wrong in this program(one of the practice program)
Resolved
Comments (1)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
11 November 2019, 05:16solution
in the first for loop:
When adding and removing items from a list using a for loop, you have to remember that the indices are automatically updated in the list. This is important because your loop index (variable I) does not automatically adjust. Lets say that you have three words in a list, words A, B, C. If you removed word A, the list would then be B, C and the next loop cycle would have I = 1. This effectively just skipped B. You can test this in action by putting two words together in the list that should be removed.
in the second for loop:
When you add a value to the list it goes to the very end. Then by using I++ in the loop body the code effectively skips the next value. Once again, to test put two values together in the list that would be duplicated and only one will.
You are going to have to fix both of these issues.
+1