简体   繁体   中英

How to print out a recursion method?

public class RecursionPracticeProgram {
    KeyboardReader reader = new KeyboardReader();

public String backString(String s){
    s = reader.readLine("String: ");
    if(s.length()==0)
        return s;

    System.out.println(backString(s.substring(1)) + s.charAt(0));   

    return backString(s.substring(1)) + s.charAt(0);


} 

public void run(){
    backString("Fox");
}

I am doing some recursion work but am having trouble printing it out. I think I have the code correct for reversing a string but when I go to run the program it just builds and doesn't actually print anything out. How do I print it out properly?

You need to make sure to only read once and you call your method at all. Just do it like this:

public class RecursionPracticeProgram {
  public void run() {
    String input = reader.readLine("String: ");
    KeyboardReader reader = new KeyboardReader();
    System.out.println(reader.backstring(input));
  }

  public String backString(String s){
    if(s.length()==0)
        return s;
    System.out.println(backString(s.substring(1)) + s.charAt(0));   
    return backString(s.substring(1)) + s.charAt(0);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM