user2816215
user2816215

Reputation: 421

Conditional statements/loop error: if and else both not reached by some elements?

console outputBasically, I had 3 arraylists: items, frequency and uniqueitems. Items contains all list of elements, eg: bread, butter, jam, butter, milk, jam. Uniqueitems contains the uniqueitems, eg: bread, butter, jam, milk. Frequency contains the number of times they occur in items, in order of uniqueitems, eg: 1,2,2,1.

But some of my elements are not going in either if or else (Jam, see image attached). And some elements, inspite of going in if, are not getting deleted from my arraylist (colddrink). It sounds silly, really. But I've been experiencing this problem since last night. Netbeans IDE. Ran my code on an online compiler as well. It gave the same answer as my IDE. So, what exactly is my mistake here? (Attached output)

int min_sup=2;
int v;

for (i=0;i<frequency.size();i++)
{
    System.out.println(uniqueitems.get(i)+ " = "+ frequency.get(i));

}

for(i=0;i<frequency.size();i++)
{
      v=frequency.get(i);
      if(v<min_sup)
      {
          uniqueitems.remove(i);
          frequency.remove(i);
          System.out.println(uniqueitems.get(i)+ " is inside if.");
      }
      else
      {
          System.out.println(uniqueitems.get(i)+ " is not in if.");
      }  
}
System.out.println("\n\n");
for(i=0;i<uniqueitems.size();i++)
{
      System.out.print(uniqueitems.get(i)+" ");  
}

Upvotes: 1

Views: 153

Answers (1)

Eran
Eran

Reputation: 393791

When you call frequency.remove(i), the previous i+1'th element in the frequency list becomes the new i'th element, which means the next iteration of your loop will skip that element, since i is incremented in each iteration.

You can handle it by decrementing i whenever you remove an element :

for(i=0;i<frequency.size();i++)
{
      v=frequency.get(i);
      if(v<min_sup)
      {
          uniqueitems.remove(i);
          frequency.remove(i);
          System.out.println(uniqueitems.get(i)+ " is inside if.");
          i--;
      }
      else
      {
          System.out.println(uniqueitems.get(i)+ " is not in if.");
      }  
}

Upvotes: 6

Related Questions