简体   繁体   English

想不出为什么我的 Java 代码会无限循环

[英]Cannot come up with why does my Java code loop infinitely

I tried to do this LeetCode daily challenge but I've found out that my code loops infinitely.我试着做这个 LeetCode 每日挑战,但我发现我的代码无限循环。

I looked through it multiple times, but I cannot find where the problem is.我多次查看它,但我找不到问题所在。 If anyone could spot it, please answer.如果有人能看出来,请回答。

public int longestValidParentheses(String s) {
    int count, highestOne = 0, index = 0;
    boolean isSevered = false;
    boolean theEnd = false;
    while(!theEnd) {
        count = 0;
        while(!isSevered) {
            if(index<s.length()-2) {
                if(s.charAt(index) == '(' & s.charAt(index++) == ')') {count = count + 2;index = index+2;}
                else {isSevered = true;}}
            else theEnd=true;isSevered=true;
        }
        highestOne = count;
    }
    return highestOne;
}

I have 2 suggestions for you:我有2条建议给你:

  1. Use indentation and do not write if/else on the same line as the code associated with them使用缩进,不要将 if/else 写在与它们关联的代码的同一行
  2. Always, ALWAYS use bracelets, even if you have only a single command.总是,总是使用手镯,即使你只有一个命令。 I think one of the wrongs java did is letting the programmers the free not to use bracelets if there is just a single command after it.我认为 java 做的一个错误是让程序员可以自由地不使用手镯,如果它后面只有一个命令。 It confusing.它令人困惑。

So you have 2 mistakes here that make your code run for infinity:因此,您在这里有 2 个错误使您的代码无限运行:

  1. isSevered will always be true after one loop exactly, as you change it to true no matter what happens as it is outside the if else statements, hence the reason I wrote the 2 advices above. isSevered在一个循环之后将始终为真,因为无论发生什么都将其更改为真,因为它在 if else 语句之外,因此我写了上面的 2 个建议。
  2. You never changing isSeveres or theEnd at the outside loop.您永远不会在外部循环中更改isSeverestheEnd Meaning that if isSevers is true and theEnd is false, you will never enter the internal while and will never exit the outside while .这意味着如果isSevers为 true 而theEnd为 false,您将永远不会进入内部while并且永远不会退出外部while

The two of those combined means that if the condition that make theEnd be initialized with true won't happen at the first run, you will be stuck with infinity loop.这两者的结合意味着如果使theEnd初始化为 true 的条件不会在第一次运行时发生,那么您将陷入无限循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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