String compression algorithm in Java
<p>I am looking to implement a method to perform basic string compression in the form of:</p>

<pre><code>aabcccccaaa -&gt; a2b1c5a3
</code></pre>

<p>I have this program:</p>

<pre><code>import java.util.Scanner;

public class Main {

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    String str = sc.nextLine();

    System.out.println(compress(str));
  }

  public static String compress(String str) {
    char[] chars = str.toCharArray();

    int count = 0;
    String result = "";

    for (int i = 0; i &lt; chars.length; i++) {
      char curr = chars[i];
      result += curr;

      for (int j = i; j &lt; chars.length; j++) {
        if (chars[j] == curr) {
          count++;
        }
        else {
          i += count;
          break;
        }
      }
      result += count;
      count = 0;
    }

    return result;
  }

}
</code></pre>

<p>But in my tests I am always missing the last character count.</p>

<p>I assume this is because the program gets out of the inner for loop before it should, but why is this the case?</p>

<p>Thanks a lot</p>