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;
}
}
}
The problem comes from str.charAt(i) + (char)count
, as they are 2 chars, they are summed up with their int
value,
Solve that by using consecutive append()
calls
str_new.append(str.charAt(i)).append(count);
You can reduce the code by using an outer for-loop
and a ternary operator in the append
, and increment only i
in the inner while
by saving i
before
int count;
for (int i = 0; i < str.length(); i++) {
count = i;
while (i < str.length() - 1 && str.charAt(i) == str.charAt(i + 1)) {
i++;
}
str_new.append(str.charAt(i)).append((i - count) == 0 ? "" : (i - count + 1));
}