Java triangle of n height using recursion

前端 未结 2 1777
暖寄归人
暖寄归人 2021-01-28 01:39

Assume the availability of a method named makeLine that can be passed a non-negative integer n and a character c and return a String consisting of n identic

2条回答
  •  闹比i
    闹比i (楼主)
    2021-01-28 02:07

    I have a problem of solving people's "homework". I'll explain how this works to help you learn.

    Here is how the code works.

    First, like you did, you must check if the value n is odd. If it is, increment the value like you have, to make it even.

    Now you need to build your 'triangle'. Do this by using recursion. For each row of the triangle, you need to print the spaces, then the 'O's, then end the line by printing the spaces.

    In your example the 'X's represent spaces, and the 'O' represent the triangle:

    OOOOO
    XOOOX
    XXOXX
    

    Furthermore, look at a bigger example:

    OOOOOOOOO
    XOOOOOOOX
    XXOOOOOXX
    XXXOOOXXX
    XXXXOXXXX
    

    As you can see, each time a new line is added, one extra space is added on each side. Therefore, you can use 'k' to your advantage to print the spaces. Added 1 to 'k' for each recursive execution, will take care of this. Now you simply have to edit your System.out.println() statement to add the makeLine so that you draw the spaces (or 'X's), as well as the 'O's.

    public void printTriangle(int n, int k){ 
        if(n <= 0)
            return;
        if(n % 2 == 0) 
            n++;
        System.out.println(makeLine(k, ' ') + makeLine(n, 'O') + makeLine(k, ' '));
        printTriangle(n-2, k+1); 
    }
    

    Hope this helps! Please feel free to ask questions if you have them.

提交回复
热议问题