Java String: Checking for consecutive letters or numbers
<p>Problem: I am playing around in Java and I am trying to count consecutive 'characters' within a string.</p>

<p>Example:</p>

<pre><code>Scanner in = new Scanner(System.in);
int n = in.nextInt();

String binaryString = Integer.toBinaryString(n);
</code></pre>

<p>The above code returns a binary string of the integer value entered. If we input the number 5 this will return: 101</p>

<p>I now wish to loop through the String and check if there are any consecutive 1's within the String.</p>

<pre><code>for (int i = 0; i &lt; binaryString.lenth(); i++)
{
    // code comes here...
}
</code></pre>

<p>I  am not sure how I can check this. I have tried the following:</p>

<pre><code>    for (int i = 0; i &lt; binaryString.length(); i++)
    {
        char charAtPos = binaryString.charAt(i);
        char charAtNextPos = binaryString.charAt(i+1);
        if (charAtPos == '1')
        {
            if (charAtPos == charAtNextPos)
            {
                consecutive += 1;
            }
        }
    }
</code></pre>

<p>But this obviously throws an ArrayIndexOutOfBounds as <code>i+1</code> will produce a number larger than the array length.</p>

<p>Thank you in advance for your answers.</p>

<p>Owen</p>