Girish Girish - 7 months ago 12
Java Question

Java Code output If input is "aabbba" then output should be "a2b3a1"

I am doing one simple java code where if

input is : "aabbba"


then

output should be: "a2b3a1"


I have done the below coding but missing somewhere. So let me know my mistake.

public class Test {
public static void main(String[] args) {

String str = "aabbba";
int count = 1;
for (int i = 0; i < str.length(); i = i + count) {
count = 1;
for (int j = i + 1; j < str.length(); j++) {
if (str.charAt(i) == str.charAt(j)) {
count = count + 1;
} else {
System.out.println(str.charAt(i) + "" + count);
break;
}
}//end of inner for

}//end of outer for
}//end of main
}//end of class

Answer

Actually you have too much code, You only need one loop, and you should be comparing the letter to the previous one, not attempting to compare each letter to every letter after it.

If you are confused about what your program is doing, the best place to start is to use your debugger to step through the code.

for(int i = 0, count = 1; i < str.length(); i++, count++) {
    char ch = str.charAt(i);
    char next = i + 1 < str.length() ? str.charAt(i + 1) : (char) -1;
    if (ch != next) {
       System.out.print("" + ch + count);
       count = 0;
    }
}