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

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -