0

Basically I am checking to see if the first x in a string is followed by another x.

When the index of the character array gets to the first x it should add 1 to 'count' and exit out of the while loop.

When I tried stepping into it, I see that despite 'firstX' being equal to 1 it goes back to the for loop and not the while loop. Then it even makes 'firstX' equal to 2.

String str = "axxbb";
char[] charArray = str.toCharArray();
int firstX = 0;
int secondX = 0;

while (firstX < 1) {
    for (int i = 0; i < charArray.length - 1; i++) {
        if (charArray[i] == 'x') {
            firstX = firstX + 1;
            // firstX becomes 1 here after detecting the first x in the string
            secondX = i + 1; 
        }
    }
}
PM 77-1
  • 12,933
  • 21
  • 68
  • 111
  • 5
    The while condition is only checked once per turn of the while-loop. The whole for-loop runs in that turn. – khelwood Aug 31 '21 at 21:58

3 Answers3

1

The inner for loop would continue to execute until it finishes, then the while condition would be re-evaluated. You could break out of the for loop when your condition is met.

outlaw
  • 197
  • 8
0

Try using>>>

String str = "axxbb";
char[] charArray = str.toCharArray();
int firstX = 0;
int secondX = 0;

while (firstX < 1) {
    for (int i = 0; i < charArray.length - 1; i++) {
        if (charArray[i] == 'x') {
            firstX = firstX + 1;
            // firstX becomes 1 here after detecting the first x in the string
            secondX = i + 1; 
            break;
        }
    }
}
Fatin Ishrak Rafi
  • 339
  • 1
  • 3
  • 11
0

You want to exit on either of two different condition being met. Try combining your loops.

String str = "axxbb";
char[] charArray = str.toCharArray();
int firstX = 0;
int secondX = 0;
int i = 0
while (firstX < 1 && i < charArray.length - 1) {
    if (charArray[i] == 'x') {
        firstX = firstX + 1;
        // firstX becomes 1 here after detecting the first x in the string
        secondX = i + 1; 
    }
    i++;
}

Note you'll still have an index out of bounds problem with

String str = "abbx";

Have you considered using a regex function? Get the index of a pattern in a string using regex

Chuck Brown
  • 353
  • 1
  • 5