Shivangi Awasthi Shivangi Awasthi - 1 year ago 47
Java Question

I want to decompress a string like ab2cd3 to ababcdababcdababcd


Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.substring(Unknown Source)
at start.compress.main(compress.java:16)


I;m getting this error my code:

package start;
import java.util.*;

public class compress {
public static void main(String args[]) {
int i, j;
Scanner v = new Scanner(System.in);
String s = v.next();
String sum = "";
for(i = 0;i < s.length(); i++) {
int k = s.charAt(i);
if(k >= 48 && k <= 57) {
for(j = 1;j < k; j++)
sum = sum + s.substring(0, i);
}

String c = k - 48 + "";
s = s.replaceFirst(c, sum);
}

System.out.println(s);
v.close();
}
}

Answer Source

You need to change increment in your for(j=1; j<k; i++) to for(j=49; j<k;j++). However, this itself will not produce the expected result. You will need to clear the sum variable in each of the outer iteration. The below code will give the expected result

public static void main(String[] args) {
    int i,j;
    Scanner v=new Scanner(System.in);
    String s=v.next();

    for(i=0;i<s.length();i++)
    {
        String sum = "";
        int k=s.charAt(i);
        if(k>=48 && k<=57)
        {
            for(j=49;j<k;j++)
                sum=sum+s.substring(0,i);
        }
        String c=k-48+"";
        s=s.replaceFirst(c,sum);
    }

    System.out.println(s);
    v.close();

}

Input: ab2cd3 Output: ababcdababcdababcd