java - why the for loop getting skipped? -
i want add products array in specific order(from smallest largest) reason code skip loop shifting part. tried make condition " products.length-2 " 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; } } }
let's consider products
array contains 2 elements. first iteration of inner for
loop:
for(int j=products.length-1; j<=0; j--){
will evaluate to:
for(int j = (2) - 1; j<=0; j--){
so can see, terminating condition origin of problem. , since you're counting backwards, should j >= 0
, not j <= 0
:
for(int j=products.length-1; j >= 0; j--){ // j >= 0 products[j+1]= products[j]; }
Comments
Post a Comment