Java Exercise: Printing asterisks Triangle and its inverted triangle using recursion method

后端 未结 2 746
再見小時候
再見小時候 2021-01-25 15:17

I need to print a triangle and its inverted triangle (standing on its tip). I manage to print out only the triangle. I know I can easily use for loop but I want to know how to m

2条回答
  •  温柔的废话
    2021-01-25 15:52

    You have to rethink the problem, this could be a possible solution:

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

提交回复
热议问题