2014-12-28 77 views
0

我正在進行練習,並且遇到了一些問題。下面的代碼給了我一個stackoverflow錯誤,但我不知道爲什麼,因爲我的代碼應該停止。通過選項循環時出現StackOverFlowError

class Options { 
    private int amount; 
    private ArrayList<Integer> pieces; 

    public void execute() { 
     pieces = new ArrayList<Integer>(); 
     pieces.add(5); 
     pieces.add(2); 
     pieces.add(3); 
     amount = pieces.size(); 
     combinations(new StringBuilder()); 
    } 

    public void combinations(StringBuilder current) { 
     if(current.length() == pieces.size()) { 
      System.out.println(current.toString()); 
      return; 
     } 

     for(int i = 0; i < amount; i++) { 
      current.append(pieces.get(i)); 
      combinations(current); 
     } 
    } 
} 

它只打印第一個輸出(555)。

謝謝。

回答

3

添加了一回結束你的遞歸

public void combinations(StringBuilder current) { 
    if(current.length() == pieces.size()) { 
     System.out.println(current.toString()); 
     return; // <-- like so. 
    } 

    for(int i = 0; i < amount; i++) { 
     current.append(pieces.get(i)); 
     combinations(current); 
    } 
} 

或將循環在else

public void combinations(StringBuilder current) { 
    if(current.length() == pieces.size()) { 
     System.out.println(current.toString()); 
    } else { 
     for(int i = 0; i < amount; i++) { 
      current.append(pieces.get(i)); 
      combinations(current); 
     } 
    } 
} 

編輯

static class Options { 
    private List<Integer> pieces; 

    public void execute() { 
     pieces = new ArrayList<>(); 
     pieces.add(5); 
     pieces.add(2); 
     pieces.add(3); 
     combinations(new StringBuilder()); 
    } 

    public void combinations(StringBuilder current) { 
     if (current.length() == pieces.size()) { 
      System.out.println(current.toString()); 
     } else { 
      for (int i = current.length(); i < pieces.size(); i++) { 
       current.append(pieces.get(i)); 
       combinations(current); 
      } 
     } 
    } 
} 

public static void main(String[] args) { 
    Options o = new Options(); 
    o.execute(); 
    System.out.println(o.pieces); 
} 

輸出是

523 
[5, 2, 3] 
+0

我怎麼能忘記,哈哈。它不工作,但... –

+0

@BartWesselink不會拋出'StackOverFlowError'了嗎? –

+0

不幸的是,它仍然如此。 線程「main」中的異常java.lang.StackOverflowError –