简体   繁体   English

遍历选项时出现StackOverFlowError

[英]StackOverFlowError when looping through options

I'm working on an exercise and I'm running into something. 我正在练习,却遇到了一些问题。 The following code gives me a stackoverflow error, but I have no idea why because my code should stop. 以下代码给了我一个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);
        }
    }
}

It only prints the first output (555). 它仅打印第一个输出(555)。

Thanks. 谢谢。

Add a return to end your recursion 添加退货以结束递归

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

or put the loop in an else like 或将循环放在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);
        }
    }
}

Edit 编辑

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

Output is 输出是

523
[5, 2, 3]

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

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