java - 循环选项时出现 StackOverFlowError

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

谢谢。

最佳答案

添加一个返回来结束递归

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]

关于java - 循环选项时出现 StackOverFlowError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27680167/

相关文章:

java - 如何在hadoop中设置默认的Java选择而不在运行时重叠

c# - Unity Networking : Unity crashes when I call the NetworkManager. singleton.StopClient() 函数

java - 双 SOA 客户端调用出现 SSL 握手错误

java - 即使条件为真也不执行 if 语句

c - 添加动态变量时 C 列表的堆栈溢出

java - 在 Java 中获取 StackOverFlowError

java - 为什么这个方法打印 4?

java - 如何消除快速排序实现中的堆栈溢出?

java - 出现内存不足异常的根本原因是什么?我们怎样才能克服这个问题呢?

java - 在 Tomcat 上部署 WAR