简体   繁体   中英

While loop with boolean not terminating

I am writing a program to remove consecutive duplicate characters in a String using below program:

static void main(String[] args){

String s = "abcdeedcbfgf";
removeConsecutiveDuplicate(s);

}

    static void removeConsecutiveDuplicate(String s) {
        String tmp = "";
        boolean isEligible = false;
        for (int i = 0; i < s.length() - 1; i++) {
            if (s.charAt(i) == s.charAt(i + 1)) {
                tmp = s.substring(0, i) + s.substring((i + 2), s.length());
                System.out.println(tmp);
                s = tmp;
                isEligible = true;
                break;
            } 
        }

        System.out.println("s is:" + s);
        while ( isEligible)
            removeConsecutiveDuplicate(s);
    }

The output should be: afgf when there are no consecutive characters and it should stop as I am using flag in while. But the flag is getting true value.

I don't know how is it doing it?

Can somebody help me understand where I am doing something wrong?

While loop is while(true) . You are never making it false . once iseligible is true , You are running into a infinite loop . change while to if . while(iseligible) => if(iseligible) .

The fix is to return the new String from your method:

static String removeConsecutiveDuplicate(String s) {
    // existing code, except...
    return tmp;
}

Then in the calling method, check if it changed :

String s = "abcdeedcbfgf";

while (true) {
    String next = removeConsecutiveDuplicate(s);
    if (next.equals(s))
        break;
    s = next;
}

Remove the variable and concept of isEligible entirely.


Also, you don't need to specify the second parameter to substring() , because if omitted "to end of String" is implied, that is:

s.substring(i, s.length())

Is identical to

s.substring(i);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM