【问题标题】:recursive method to display a string backwards but while loop doesn't work向后显示字符串但while循环不起作用的递归方法
【发布时间】:2016-03-10 04:43:15
【问题描述】:

我尝试编写一个递归方法来向后显示字符串的内容。而且我不明白为什么方法中的while循环不能按我的预期工作,它一直在循环。 但是,如果我使用 if/else 循环,它似乎工作得很好。 但我只是想了解 while 循环会发生什么。

 public class printString{

    void BitString(String a, int i){
        while (i > 0){
            System.out.println(i);
            //System.out.println(a.substring(i-1, i));
            i--;
            BitString(a.substring(0, i), i);
        }
        return;
    }

    public static void main(String args[]){
        printString print = new printString();

        String str = "I am a beginner.";
        int i = str.length() -1;

        print.BitString(str, i);
    }
}

【问题讨论】:

    标签: string if-statement recursion while-loop


    【解决方案1】:

    位修改代码。

    这里缺少 4 件事

    1) 获取子字符串 什么 substring 方法说:子字符串从指定的 beginIndex 开始并延伸到索引处的字符 endIndex - 1 这里每次 last char 丢失,因为那个 index out of range 的异常正在发生

    2)在substring方法后,count(length)应该减少,同时传递参数

    3)return 语句丢失..!!,必须有return 语句否则程序运行无限次。

    4)while 条件 while (i >= 0)

    void BitString(String a, int i){
    
        while (i >= 0){
            System.out.print(a.charAt(i));
            //i--;
            BitString(a.substring(0, i), --i);
            return;//Missing return
    
        }
        return;
    }
    

    【讨论】:

    • 哇!感谢您的旅游解释。我还有 1 个问题。3)return 语句丢失..!!,必须有 return 语句否则程序运行无限次。
    • 在我的原始代码中,我想当我设置while(i> 0),并且i减少到0时,它不会进入while循环,然后程序会在外面运行return语句while 循环,因此不会无限循环。但这并没有发生......我只是有点困惑。
    猜你喜欢
    • 2017-01-25
    • 1970-01-01
    • 1970-01-01
    • 2013-08-12
    • 2014-05-24
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多