mercredi 1 avril 2015

Recursion - WHY does this print the output backwards?

Can somebody explain why this program outputs ZYx321cBa instead of: aBc123xYZ


I dont seem to understand why. I notice when the recursion is called at the end of the method, it prints properly, but not when recursion is called first.



public class R {

public static void main(String[] args) {

String str ="aBc123xYZ";

Rc rev = new Rc(str);
rev.raC(0);
}
}


Second class, that prints the string based on the index entered in previous class



class Rc {

String s;
int lc = 0;

Rc(String s) {
this.s = s;
}

void raC(int index) {
if (index != s.length()) {
raC(index + 1);
//System.out.println(index);
System.out.println(s.charAt(index) + " ");
if(Character.isLowerCase(s.charAt(index))) {
lc ++;
}
}

if (index == 0) {
System.out.println(":" + lc);
}
}
}

Aucun commentaire:

Enregistrer un commentaire