2012-07-30 103 views
0

我有recrusive功能工作正常。問題是當行數很大時它給出了stackoverflow錯誤。我想把它放在迭代中,可能使用for循環。在做這件事時需要一些幫助。該方法的更改遞歸方法迭代

private TreeSet validate(int curLine, TreeSet errorSet) { 
    int increment = 0; 
    int nextLine = 0; 

    if (curLine == lines.length || errorSet.size() != 0) { 
     return errorSet; 
    } else { 
     String line = lines[curLine]; 

     //validation starts. After validation, line is incremented as per the requirements 

     increment = 1 //As per requirement. Depends on validation results of the line 

     if (increment > 0) { 
      try{ 
       Thread.currentThread().sleep(100); 
      }catch(Exception ex){ 
       System.out.println(ex); 
      } 
      nextLine = (curLine + increment); 
      validate(nextLine, errorSet); 
     } 
    } 

    return errorSet; 
} 

海報的描述:

的方法確實驗證文本行,這些行有多少行已被跳過,如果該行是有效的指令。所以,如果該行是有效的,許多行將被跳過使用增量。如果行是無效的增量將是0

+1

您正在調用'validate(nextLine,errorSet)'而不保存其返回值。這是故意的嗎?另外,由於前面的行,'if(increment> 0)'總是成立的:'increment = 1'。解釋該方法應該做什麼可能是一個好主意。 – 2012-07-30 16:12:40

+0

它工作正常,所以我沒有保存它。 – FirmView 2012-07-30 16:17:17

+0

增量不會總是> 0.如果行中有錯誤,則增量爲0. – FirmView 2012-07-30 16:19:15

回答

2

我不知道爲什麼,這是擺在首位不斷遞歸。這非常適合使用FOR循環。使用像這樣:

private TreeSet validate(int curLine, TreeSet errorSet) { 
    int increment = 0; 

    if (errorSet.size() != 0) 
     return errorSet; 

    for (int curLine = 0; curLine < lines.Length; curLine += increment) 
    { 
     // put your processing logic in here 


     // set the proper increment here. 
    } 
} 

如果增量總是將是1,那麼你可以只用curr++代替curLine += increment

1
for(String line : lines) { 
    // validate line here 

    if(!errorSet.isEmpty()) { 
    break; 
    } 
} 
1

你的問題的解決方案可能是簡單的for循環或while ,用於停止條件的邏輯表達式。通常,當我們必須通過Iterable或數組的所有元素時,我們使用for循環。如果我們不知道我們要做多少循環,我們使用while循環。對於遍歷時的優勢,是我們的自由已經局部變量,所以我們沒有CA他們使用圈外的一面,因此,我們減少的可能性有一些bug。

您的問題是,你必須打破兩個條件的程序:

  1. 當errorSet不是空的。
  2. 當線的陣列具有不再項目。

至於矛盾,我們可以說,你的程序應該繼續:

  1. 直到errorSet是空的,
  2. ,直到行數小於它們的存儲陣列的尺寸。

這爲我們提供了簡單地表達

  1. errorSet.isEmpty()
  2. lineNumber < lines.length()

我們可以通過邏輯運算符&&將它們組合起來,並在for循環停止規則中使用。

for(int lineNumber= 0; errorSet.isEmpty() && lineNumber< lines.length(); lineNumber++) { 

    //code to operate 

} 

注:

典型地,對於邏輯表達式被用於操作者&&,即確保該邏輯表達式的每一個部分進行評價。這另一種方法是&,在虛假的情況下,不要操作時間更長,返回false。我們可能會試圖使用這個運算符來表達這個表達式,但我會是個壞主意。因爲當我們遍歷所有行而沒有錯誤時,代碼將生成IndexOutOfBoundException,如果我們切換位置,那麼我們不會有任何優化,因爲第一個表達式將被評估的次數相同。