Owen Nel Owen Nel - 3 months ago 15
Java Question

Java String: Checking for consecutive letters or numbers

Problem: I am playing around in Java and I am trying to count consecutive 'characters' within a string.

Example:

Scanner in = new Scanner(System.in);
int n = in.nextInt();

String binaryString = Integer.toBinaryString(n);


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

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

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


I am not sure how I can check this. I have tried the following:

for (int i = 0; i < binaryString.length(); i++)
{
char charAtPos = binaryString.charAt(i);
char charAtNextPos = binaryString.charAt(i+1);
if (charAtPos == '1')
{
if (charAtPos == charAtNextPos)
{
consecutive += 1;
}
}
}


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

Thank you in advance for your answers.

Owen

Answer

try running the for loop for size one less than the length of the strin

 for (int i = 0; i < (binaryString.length()-1); i++)
{
    char charAtPos = binaryString.charAt(i);
    char charAtNextPos = binaryString.charAt(i+1);
    if (charAtPos == '1')
    {
        if (charAtPos == charAtNextPos)
        {
            consecutive += 1;
        }
    }
}