I am trying to write a program in Java that decompresses a compressed RLE statement using recursion, but I am continuously getting stack overflow errors and I do not know why.
Here is what I wrote thus far:
public class StringRec
{
public static void main (String args[]){
System.out.println(decompress("wed4d"));
}
//Version 0.1
public static String decompress(String compressedText)
{ String cText = compressedText;
StringBuffer newString = new StringBuffer();
int i = 0;
if (cText==""){return newString.toString();}
if(!cText.isEmpty()){
if(Character.isLetter(cText.charAt(i))){
newString.append(cText.charAt(i));
cText = cText.substring(1,cText.length());
return decompress(cText);
//remove first letter, return new modified string with removed first letter to decompress.
}
if(Character.isDigit(cText.charAt(i))){
int c = cText.charAt(i)-'0';
if (c==0){
cText = cText.substring(2,cText.length());}
return decompress(cText);
//delete c and the letter after it and send new modified string to decompress.
}
}else {
newString.append(cText.charAt(i+1));
int c = cText.charAt(i);
c--;
String num = ""+c;
cText = cText.replaceFirst(num, Character.toString(cText.charAt(i)));
return decompress(cText);
//appends character after number to newString, decrements the number and returns
//the new modified string to decompress with the first number decremented by one
}
return newString.toString();
}
}
My base case for the recursion is an empty string, if the string starts with a letter that letter is added to the stringbuffer newString only once and that first letter of the original string is deleted from the string sequence and the new string is passed to decompress; if it starts with a number that is zero then the first two chars of the string are deleted and the new string is passed to decompress.
If it's a number greater than 0[else] then the letter in front of it is added to the stringbuffer newString and the number is decremented and replaces the number in the beginning of the string and passes the new string [with the original first char number - 1] to decompress.
decompressrecursively, the recursive routine will create a newnewString. The new call of the routine will not append to the samenewStringthat the old call was using. Your recursive method will probably need to takenewStringas a parameter that it keeps passing to itself, and then an outside non-recursive routine will need to initialize it before calling the recursive routine for the first time.System.out.printlnlogging calls would help you find out why your recursion is not reaching the base case and causing the error...