[英]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. 输出应为: afgf当没有连续字符时,它应停止,因为我在while中使用flag。 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) . While循环为while(true)。 You are never making it false .
您永远不会把它弄错。 once iseligible is true , You are running into a infinite loop .
一旦iseligible为true,您就会陷入无限循环。 change while to if .
更改为if。 while(iseligible) => if(iseligible) .
while(符合条件)=> if(符合条件)。
The fix is to return the new String from your method: 解决方法是从您的方法返回新的String:
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. 完全删除
isEligible
的变量和概念。
Also, you don't need to specify the second parameter to substring()
, because if omitted "to end of String" is implied, that is: 另外,您不需要将第二个参数指定为
substring()
,因为如果省略,则意味着“ to String of end”,即:
s.substring(i, s.length())
Is identical to 等同于
s.substring(i);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.