简体   繁体   中英

Why is my result string not updating in my recursive method?

I have my recursive method for deleting consecutive characters almost how my professor wants it. However, she doesn't want print statements in the removeDuplicates method, and I can't figure out why my result string isn't updating before it returns. Here is my code:

public static void main(String[] args){

    System.out.println(removeDuplicates("a"));
    System.out.println(removeDuplicates("aa"));
    System.out.println(removeDuplicates("aab"));
    System.out.println(removeDuplicates("aabb"));
    System.out.println(removeDuplicates("aaaba"));
    System.out.println(removeDuplicates("aabbccdefghijkllaa"));
    }

public static String removeDuplicates(String a){

    int beg=0;
    String result="";

    if (a.length()-1 ==0){
        result=""+a.charAt(0);
         //System.out.print(a.charAt(0));
      }
    else if (a.charAt(beg) == a.charAt(beg+1)) {
          beg++;
          removeDuplicates(a.substring(beg, a.length()));
         }
    else {
       result=""+a.charAt(0);
       //System.out.print(result);
       beg++;
       removeDuplicates(a.substring(beg, a.length()));
      } 
   return result;
    }
    }

I see that each time it starts, it resets result to an empty string. However, not initializing it gives an error because the return line doesn't recognize that the string was updated. How can I fix this? (Everything else is how it's supposed to be. No static variables, the calling in the main method is correct, etc. I just need that one part fixed.)

Your removeDuplicates need to handle the return value of your recursive call

in the location :

beg++;
removeDuplicates(a.substring(beg, a.length()));

you need to store the result of the removeDuplicates calls

PS: I won't write the answer as it is homework question, I am merely pointing where to look at

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