2017-10-11 22 views
0

我正在处理递归问题。在编写请求的代码之后,我所从事的网站运行带有不同值的代码作为输入。但是,第一次运行正常,但所有后续运行将第一次运行的返回值与后续每次运行的值连接起来。使用递归获取以前的返回值与新值连接

我也在最后得到堆栈溢出错误。

我需要帮助!

下面是代码:

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

任何帮助是极大的赞赏。

+0

尝试在'main()'中放入'returnValue =“”;''。 –

+0

当我运行代码时,它只是打印'这很有趣'。这正是你的代码所做的。 '你期望什么结果btw? –

+2

提示:'static' .. – 2017-10-11 13:03:40

回答

1

您需要将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); 
    } 
} 
+0

这样做!谢谢 – user182162

0

如果您习惯使用表达式:

如果这是正确的解决方案,那么你可以整理一下

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

,你可以摆脱静态属性的!