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

后端 未结 2 652
再見小時候
再見小時候 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:39

    I would recommend to keep the creation of the resulting String separate from printing. That would allow you to do anything else you want with the result and it's likely to be more efficient. Also for efficiency, StringBuilder is recommended as it avoids creating and discarding many String objects. Also for efficiency prefer appending a single char instead of a String with a single char.

    Here is a solution with these in mind. You pass as argument an initial count of zero, the number of lines and a new StringBuilder. The number of * appended increases up to half the number of lines and then decreases. New line is appended in each recursive call.

    public void doIt() {
        String p = nums(0, 7, new StringBuilder());
        System.out.print(p);
    }
    
    public String nums(int counts, int lines, StringBuilder b) {
        if (counts == lines)
            return b.toString();
    
        int size = counts < lines / 2 ?
                   counts :
                   lines - counts - 1;
    
        for (int i = 0; i < size + 1; ++i)
            b.append('*');
        b.append('\n');
    
        return nums(counts + 1, lines, b);
    }
    
    0 讨论(0)
  • 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;
    }}
    
    0 讨论(0)
提交回复
热议问题