gpt4 book ai didi

java - 循环选项时出现 StackOverFlowError

转载 作者:行者123 更新时间:2023-12-01 22:31:18 26 4
gpt4 key购买 nike

我正在做一项练习,但遇到了一些问题。下面的代码给了我一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com