java - Questions about While,break
習慣沉默
習慣沉默 2017-05-17 10:02:00
0
2
566

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

習慣沉默
習慣沉默

reply all(2)
黄舟

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

洪涛

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!