m0_45696744 2021-04-16 20:43 采纳率: 50%
浏览 58
已采纳

Java写递归出现“java.lang.StackOverflowError”

目的是用递归写一个扰乱字符串

public String getScramble(String s) {
        //如果字符串长度为1,返回其本身
        if(s.length()==1) {
            return s;
        }
        //产生随机数
        int index = (int)(Math.random()*s.length());
        String s1 = s.substring(0, index);
        String s2 = s.substring(index);
        //随机决定是s=s1+s2还是s=s2+s1
        if(Math.random() > 0.5) {
            s = getScramble(s2) + getScramble(s1);
        } else {
            s = getScramble(s1) + getScramble(s2);
        }
        return s;
    }
  • 写回答

3条回答 默认 最新

  • 关注

    写一些打印语句,把过程的s打印出来看看。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?