循环选项时的StackOverFlowError

时间:2014-12-28 20:09:34

标签: java stack-overflow

我正在做一个练习,而且我遇到了什么。下面的代码给了我一个stackoverflow错误,但我不知道为什么,因为我的代码应该停止。

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)。

感谢。

1 个答案:

答案 0 :(得分: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]