Why is my if loop is getting skipped while my condition is true?

skip for loop
while loop javascript
c programming if statement multiple conditions
node while loop continue
illegal continue statement: no surrounding iteration statement
javascript break out of do while loop
parsing error: unsyntactic continue
javascript continue foreach

I am coding a small program where I add an an ArrayList of Strings and I have a method that removes every String ending with S, it is working fine for 4 of elements but it seems to skip one.

Minimum reproducible example:

import java.util.ArrayList;
public class sList {
    public static void main(String [] args) {

    ArrayList<String> sList=new ArrayList<String>();

    sList.add("leaf");
    sList.add("leaves");
    sList.add("box");
    sList.add("boxes");
    sList.add("phones");
    sList.add("phone");
    method m=new methods(); 
System.out.println(m.removePlurals(sList));

}
}

\\ that is my main method 

import java.util.ArrayList;

public class method {

ArrayList<String> removePlurals(ArrayList<String> s) {

        for (int i = 0; i < s.size(); i++) {
            char c = s.get(i).charAt(s.get(i).length() - 1);
            if (c == 's') {
                s.remove(i);
            }

        }
        return s;
    }

}

I am getting as an output: [leaf, box, phones, phone] so it is skipping "phones" Any help?

Think about what happens when after you removed "boxes" from the list. The index of "phones" decreases by 1. If it is originally the nth item in the list, it is now the (n-1)th item in the list, isn't it? So now "phones" is at the same position in the list as where "boxes" originally was. On the other hand, i increases by 1.

Now you should see the problem, to check for "phones", i should remain the same because after removing "boxes", the index of "phones" decreased by 1.

Solution, just loop from the end of the list to the start, and you won't have this problem:

for (int i = s.size() - 1; i >= 0; i--) {
    char c = s.get(i).charAt(s.get(i).length() - 1);
    if (c == 's') {
        s.remove(i);
    }

}

Skip a while loop if the condition is not met at the start, Hi, I have a while loop that has the condition “while A=True”. and A=False it should do nothing within the loop (skip instead of doing once). Jeff Verdegan wrote:I don't know which for loop you think is being skipped, but given for (initialization; condition; increment), if the loop's body is never being entered, then condition is false when we first hit that for statement. Apologies Jeff. The for loop that gets skipped is the second one.

It is because at the moment you remove an item of a list, the list size is less than at the begining and when your counter is incremented, points to the next one element (skips one). Yous can solve that just looping the list on the other way, as follow:

 ArrayList<String> removePlurals(ArrayList<String> s) {

        for (int i = s.size()-1; i >= 0; i--) {
            char c = s.get(i).charAt(s.get(i).length() - 1);
            if (c == 's') {
                s.remove(i);
            }

        }
        return s;
    }

}

Combinatorial Pattern Matching Algorithms in Computational Biology , Back to the rna_to_protein subroutine, the previous while loop for skipping any nucleotides before the first start codon was correct only if the $rna string In order to skip nucleotides within the $rna string only, an additional condition is needed  If the user enters a negative loop count, the program skips the loop entirely. That’s because the specified condition is never true, so control never enters the loop. In addition, if the user enters a very large number, the program loops for a long time before completing.

This is happening because the list you are iterating is being updated in the same loop. So when you remove one element is previous iteration it's index is being updated and element is not picked up at all by loop. So the solution should be like:

1) Create new list and return that:

ArrayList<String> removePlurals(final ArrayList<String> s) {

    final ArrayList<String> updatedList = new ArrayList<String>();

    for (int i = 0; i < s.size(); i++) {
      final char c = s.get(i).charAt(s.get(i).length() - 1);
      if (c != 's') {
        updatedList.add(s.get(i));
      }

    }
    return updatedList;
  }

2) Using Iterator:

ArrayList<String> removePlurals(final ArrayList<String> s) {

        final Iterator<String> itr = s.iterator();
        while (itr.hasNext()) {
        final String x = itr.next();
        if (x.charAt(x.length() - 1) == 's') {
           itr.remove();
        }
        }
        return s;  
      }

Skipping if statement, while loop. temp_fuel being a linked list of structs that hold a name. As I step through I see it skip over the whole if statement. It doesn't flag == 1;. As far as I can tell it does nothing if the condition in the if statement is true. In do while loop first the statements in the body are executed then the condition is checked. If the condition is true then once again statements in the body are executed. This process keeps repeating until the condition becomes false. As usual, if the body of do while loop contains only one statement, then braces ({}) can be omitted.

Aside from the issue reported in the question: you have the issue that removing from the middle of an ArrayList one element at a time is really inefficient, because you keep on shifting all of the elements between (i+1) and the end of the list along by one position - and then you do it again for most of them.

Performance should not be your first concern - slow, correct code is always better than fast, incorrect code - but you should keep in the back of your mind issues that some things are worth avoiding: in this case, it is repeated removal from the middle of an ArrayList.

A better solution is not to keep shifting the elements, but rather just to move them once.

Unlike the solutions which iterate the list backwards, this can be done iterating forwards, which feels more natural (to me, at least).

int target = 0;
for (int i = 0; i < s.size(); ++i) {
  if (!s.get(i).endsWith("s")) {
    s.set(target, s.get(i));
    target++;
  }
}

This shifts each element that you are going to keep to its new position. All that then remains is to chop off the end of the list:

while (s.size() > target) s.remove(s.size()-1);

Or, in a single operation:

s.subList(target, s.size()).clear();

All together:

int target = 0;
for (int i = 0; i < s.size(); ++i) {
  if (!s.get(i).endsWith("s")) {
    s.set(target, s.get(i));
    target++;
  }
}
s.subList(target, s.size()).clear();

Note that this is effectively what is done by ArrayList.removeIf:

s.removeIf(e -> e.endsWith("s"));

(removeIf does a little bit more, in that it does the removal in a failure-atomic way, that is, if the e.endsWith fails for some reason, such as a null element, the list is left untouched rather than partly updated).

ActionScripting in Flash MX, There's a logical problem with this code as each if statement is encountered (and If the various conditions were exclusive — that is, when one is true, the others condition is met, the others aren't even considered — they're simply skipped. If the condition evaluates to true then the code returns to the Do line and runs through the loop again. The difference between having the condition on the Do line and on the Loop line is very simple When the condition is on the Do line, the loop may not run at all. So it will run zero or more times.

JavaScript continue Statement, Loop through a block of code, but skip the value of "3": In a while loop, the condition is tested, and if it is true, the loop is executed again; In a for loop, the  In while loop, a condition is evaluated before processing a body of the loop. If a condition is true then and only then the body of a loop is executed. After the body of a loop is executed then control again goes back at the beginning, and the condition is checked if it is true, the same process is executed until the condition becomes false.

Control Structures - ChucK, The if statement executes a block if the condition is evaluated as non-zero. here is an infinite loop while( true ) { // your code loops forever! condition if( condition ) continue; // some great code that may get skipped (if continue is taken) }  When a while loop is encountered, <expr> is first evaluated in Boolean context. If it is true, the loop body is executed. Then <expr> is checked again, and if still true, the body is executed again. This continues until <expr> becomes false, at which point program execution proceeds to the first statement beyond the loop body. Consider this

Python break, continue and pass Statements, The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while​  I am working on a program that uses two objects of a custom class template List [which is a linked list, with each item pointing to the next] and concatenates them. Initially, I need to input numbers into my main function, so I have two sets of while loops (while an EOF sequence is not entered) to

Comments
  • If you remove something from the list the index is not adjusted. That means you will have to add a i-- or else you skip an element.
  • An easier way to implement this is s.removeIf(e -> e.endsWith("s"));.