This is the problem:
while(str.charAt(i)==ch)
That will keep going until it falls off the end... when i
is the same as the length of the string, it will be asking for a character beyond the end of the string. You probably want:
while (i < str.length() && str.charAt(i) == ch)
You also need to set count
to 0 at the start of each iteration of the bigger loop - the count resets, after all - and change
count = count + i;
to either:
count++;
... or get rid of count
or i
. They're always going to have the same value, after all. Personally I'd just use one variable, declared and initialized inside the loop. That's a general style point, in fact - it's cleaner to declare local variables when they're needed, rather than declaring them all at the top of the method.
However, then your program will loop forever, as this doesn't do anything useful:
str.substring(count);
Strings are immutable in Java - substring
returns a new string. I think you want:
str = str.substring(count);
Note that this will still output "a2b2a2" for "aabbaa". Is that okay?