gpt4 book ai didi

java - 使用递归获取先前的返回值与新值连接

转载 作者:行者123 更新时间:2023-12-02 12:09:00 26 4
gpt4 key购买 nike

我正在解决递归问题。编写所请求的代码后,我正在工作的站点运行具有不同值作为输入的代码。但是,第一次运行工作正常,但所有后续运行都会将第一次运行的返回值与后续每次运行的值连接起来。

我最后还收到堆栈溢出错误。

我需要帮助!

这是代码:

package com.company;

import static java.lang.System.*;

public class Main {

public static String returnValue="";

public static void main(String[] args) {
repeat("this is fun", 1);
out.println(returnValue);
}
public static String repeat(String s, int i){
if (i==0) {
return returnValue;
}
else{
returnValue+=s;
repeat(s,i-1);
}
return returnValue;
}
}

非常感谢任何帮助。

最佳答案

您需要将static returnValue移至该方法中。然后,您需要通过捕获内部递归调用返回的字符串来控制结果。

类似于:

public static String repeat(String s, int i){
String returnValue="";
if (i==0) {
return returnValue;
}
else{
returnValue+=s + repeat(s,i-1);
}
return returnValue;
}

注意:这可能不是与您想要的等效算法,但它应该演示该技术。

如果这是正确的解决方案,那么您可以整理:

public static String repeat(String s, int i){
if (i==0) {
return "";
} else {
return s + repeat(s,i-1);
}
}

关于java - 使用递归获取先前的返回值与新值连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46688825/

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