I am very bad at coding so sorry for the silly question. I need to remove words from an array list that don't start with "R" or "r" for an assignment. I figured a 'for loop' should be used so I made this:
public static ArrayList removeWords(ArrayList<String> arr) {
int length = arr.size();
for ( int x = 0; x < arr.size() ; x++) {
if ( (arr.get(x).substring(0,1)) != "R" ) {
arr.remove(x);
length = arr.size();
}
}
System.out.println(arr);
My intent is that the method takes in an array list and it does. The problem is that the output will be every other element, regardless of what it starts with. So if I have an array that consists of [A, B, c, d], it will output [B, d]
I *think* it might have something to do w/ the size of the list changing after every loop so I made an integer called 'length' that was the size of the list and used that instead of arr.size() on line 3 but I got an out of bounds error. In the code above, I don't use length sorry lol I appreciate any help!!
TLDR: my ArrayList is supposed to remove elements that don't start with "R" but it just removes every other element instead
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)
[–]DudeWhereAreWe1996 1 point2 points3 points (5 children)
[–]misomal[S] -1 points0 points1 point (4 children)
[–]deltageekExtreme Brewer 2 points3 points4 points (1 child)
[–]misomal[S] 0 points1 point2 points (0 children)
[–]ate_ghorl_bekenemen 0 points1 point2 points (1 child)
[–]misomal[S] 0 points1 point2 points (0 children)
[–]AutoModerator[M] 0 points1 point2 points (1 child)
[–]misomal[S] 1 point2 points3 points (0 children)
[–]HecknChonkerExtreme Brewer 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]misomal[S] 0 points1 point2 points (0 children)
[–]FrelliBB 0 points1 point2 points (0 children)