簡體   English   中英

想不出為什么我的 Java 代碼會無限循環

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

我試着做這個 LeetCode 每日挑戰,但我發現我的代碼無限循環。

我多次查看它,但我找不到問題所在。 如果有人能看出來,請回答。

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;
}

我有2條建議給你:

  1. 使用縮進,不要將 if/else 寫在與它們關聯的代碼的同一行
  2. 總是,總是使用手鐲,即使你只有一個命令。 我認為 java 做的一個錯誤是讓程序員可以自由地不使用手鐲,如果它后面只有一個命令。 它令人困惑。

因此,您在這里有 2 個錯誤使您的代碼無限運行:

  1. isSevered在一個循環之后將始終為真,因為無論發生什么都將其更改為真,因為它在 if else 語句之外,因此我寫了上面的 2 個建議。
  2. 您永遠不會在外部循環中更改isSeverestheEnd 這意味着如果isSevers為 true 而theEnd為 false,您將永遠不會進入內部while並且永遠不會退出外部while

這兩者的結合意味着如果使theEnd初始化為 true 的條件不會在第一次運行時發生,那么您將陷入無限循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM