ts_928 ts_928 - 1 month ago 10
Java Question

index out of bounds exception strings 8

I'm trying to set up a compression algorithm that places a number before a char in a string when that char can be seen in succession. EX: for the string
"balloonnnnns" it would be compressed to "ba2l2o5n" but I am receiving an index out of bounds error:

for(int i = 0; i < (length-1); i++ ){
if (original.charAt(i) == original.charAt(i + 1)){
count = count + 1;
original = original.substring(i, i+1);
System.out.println(original);
System.out.println(count);
if(count > 0){
altered = count + original.substring(i);
System.out.println(altered);
}
}else{
count = 0;

Answer

As @Jon Skeet pointed out you shouldn't change your original while in the loop. You could try this way (comments on code for understanding)

Test:

public class Test
{

    public static void main ( String [ ] args )
    {
        String original = "balloonnnnns";
        int length = original.length ( );
        int count = 1;
        String altered = "";
        //Loop over all string
        for(int i = 0; i < (length-1); i++ ){
            //while they are the same
            while (original.charAt(i) == original.charAt(i + 1)){
                //count and keep going on the original string
                count++;
                i++;
                //avoid border case when last character is repeated, i.e : baaaaaaaa
                if ( i == length -1)
                {
                    break;
                }
            }
            //if they are repetead
            if(count > 1)
            {
                //add altered + count + charRepeated, i.e. a3e5t
               altered = altered +count + original.charAt(i);

            }
            else{
                //just add the normal character without count
                altered += original.charAt(i);
            }
            //add last character if not repeated
            if ( (i == length - 2) && (count > 1))
            {
                altered += original.charAt ( i+1 );
            }

            //reset counting 
            count = 1;

        }
        System.out.println ( altered );
    }
}

Output:

ba2l2o5ns