Chie
Chie

Reputation: 45

why the for loop getting skipped?

I want to add products to the array in a specific order(from smallest to largest) but for some reason the code skip the for loop that do the shifting part. I tried to make the condition " products.length-2 " but it still doesn't work.

if(products!=null){
  for(int i=0; i<products.length; i++){
    if(products[i]!=null && product.getItemNum() < products[i].getItemNum()){
      index=i;
      temp = products[index];
      for(int j=products.length-1; j<=0; j--){
        products[j+1]= products[j];
      }
      products[index]= product;
    }
  }
}

Upvotes: 0

Views: 177

Answers (1)

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17142

Let's consider that your products array contains 2 elements. The first iteration of the inner for loop:

for(int j=products.length-1; j<=0; j--){

will evaluate to:

for(int j = (2) - 1; j<=0; j--){

So as you can see, your terminating condition is the origin of the problem. And since you're counting backwards, it should be j >= 0, not j <= 0:

for(int j=products.length-1; j >= 0; j--){ // j >= 0
    products[j+1]= products[j];
}

Upvotes: 3

Related Questions