lundi 26 janvier 2015

Why does the order matter for this recursion method?

The following code is in response to a question on coding bat : http://ift.tt/1H1tc1z


This solution works...



public String changeXY(String str) {

if (str=="") {return "";}
else if (str.substring(0,1).equals("x") && str.length()<2) { return "y";}
else if (str.substring(0,1)!="x" && str.length()<2) {return str;}
else if (str.substring(0,1).equals("x") && str.length()>1) {return "y" + changeXY(str.substring(1));}
else if (str.substring(0,1)!=("x")) { return str.substring(0,1) + changeXY(str.substring(1));}


return changeXY(str);

}


However, why does the solution not work if I simply rearrange the if-statements? Surely the order doesn't matter. Could someone explain why the order matters in this instance/ in any instance.


Aucun commentaire:

Enregistrer un commentaire