Java练习:使用递归方法打印星号三角形及其倒三角形
我需要打印一个三角形及其倒三角形(位于其尖端)。我设法只打印出三角形。我知道我可以轻松地使用for循环,但是我想知道如何使用递归,在我的情况下,我不知道如何同时打印三角形和倒置三角形,谢谢。
Example desired output:*
**
***
****
****
***
**
*
我的代码:
public class Recursion1 {    public static void main(String[] args) {
        Recursion1 me = new Recursion1();
        me.doIt();
    }
    public void doIt() {        
        nums(4);
    }
    public String nums(int counts) {
        if (counts <= 0) {
            return "";
        }
        String p = nums(counts - 1);
        p = p +"*";
        System.out.print(p);
        System.out.println();
        return p;
    }
}
我的结果:
Results:*
**
***
****
回答:
您必须重新考虑问题,这可能是一种可能的解决方案:
public class Recursion1 {private static int endValue;
private static int startValue = 1 ;
public Recursion1(int endValue){
    Recursion1.endValue = endValue;
}
public static void main(String[] args) {
    Recursion1 me = new Recursion1(4);
    me.doIt();
}
public void doIt() {        
    nums("*");
}
public String nums(String value) {
    if( startValue == endValue){
        System.out.println(value);
    }else{
        System.out.println(value);
        startValue ++;
        value = value.concat("*");
        nums(value);
        value = value.substring(1);
        System.out.println(value);
    }
    return value;
}}
以上是 Java练习:使用递归方法打印星号三角形及其倒三角形 的全部内容, 来源链接: utcz.com/qa/432233.html
