Please help with the java code below.
When I give input, for example, aabbcccd,
the output is 99100102d, but it should be a2b2c3d.
Can anyone tell what's my mistake in this code? (This code tries to capture input and output how often a specific char has been typed)
import java.util.*;
public class Main {
public static void main(String args[]) {
try {
Scanner scn = new Scanner(System.in);
String s = scn.nextLine(); // taking input
StringBuilder str = new StringBuilder(s);
StringBuilder str_new = new StringBuilder();
int i = 0 ;
while (i < str.length()) {
int count = 1;
while (i < str.length()-1 && str.charAt(i) == str.charAt(i+1)){
count += 1;
i++;
}
if (count == 1)
str_new.append(str.charAt(i));
else
str_new.append(str.charAt(i) + (char)count);
i++;
}
System.out.println(str_new);
} catch (Exception e) {
return;
}
}
}