search

Home  >  Q&A  >  body text

java - Questions about While,break

Excuse me, why once the while loop of this code enters the back part of else, the subsequent while loop can no longer enter the first half branch? I think the condition after the if should be satisfied. The running result cannot be broken because it cannot enter the first loop. Asking God for advice:

public class SearchString {

public static void main(String[] args) {
    String s1 = "abcaaaaaaaabcabc";
    String s2 = "abc";
    int len = s2.length();
    int pos = 0;
    int count = 0;
    while (true) {
        if (s1.indexOf(s2, pos) == -1) {
            System.out.println("Search Over, result count=" + count);
            break;
        } else {
            System.out.println("Position" + (count + 1) + " is " + pos);
            int a = pos + len;
            pos = s1.indexOf(s2, a);
            count++;
        }
    }
}

}
The running result is -1 10 13 -1 10 13, an infinite loop

習慣沉默習慣沉默2775 days ago623

reply all(2)I'll reply

  • 黄舟

    黄舟2017-05-17 10:04:00

    Because the result cannot be matched when querying for the third time, the value returned is -1. If the second parameter of indexOf() is less than 0, it will be treated as 0.
    So the first cycle begins again.

    You can debug with breakpoints, the result will be very clear

    reply
    0
  • PHP中文网

    PHP中文网2017-05-17 10:04:00

    When entering the second loop, else is entered, and pos becomes 13. The next loop, that is, when entering the third loop, it still enters else.
    This time, a becomes 16 in else, and pos is -1. The next loop s1, indexOf(s2, pos) is 0, and it still enters else, so an infinite loop is generated.

    I think you need not to change pos in else every time, but directly intercept the second half of the s1 string.

    reply
    0
  • Cancelreply