Reputation: 15
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;
Upvotes: 0
Views: 73
Reputation: 1987
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)
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 );
}
}
ba2l2o5ns
Upvotes: 2
Reputation: 469
The first time your loop gets executed, you update string named 'original' with the first character of actual 'original' string. For eg. if String original = "aaa" - after loop executes for 0, value for original becomes 'a'!
You can refer this for solutions: Java compressing Strings
Upvotes: 0