Java: Printing triangles and spaces by calling methods

mightymorphinParkRanger :

I'm stuck on this question:

Printing stars and spaces

Define a method called printSpaces(int number) that produces the number of spaces specified by number. The method does not print the line break.

You will also have to either copy the printStars method your previous answer or reimplement it in this exercise template. Printing a right-leaning triangle

Create a method called printTriangle(int size) that uses printSpaces and printStars to print the correct triangle. So the method call printTriangle(4) should print the following: Sample output

>    *
>   **
>  ***
> ****

I cannot get the spaces thing to work on the first question, and I'm totally lost on making the recursive triangle. I see that lots of answers are using for loops, however the class I'm working in wants them done as methods. I can't comprehend how to properly translate that. I got the triangle the other way around with this:

public class Test072 {

    public static void main(String[] args) {
        printTriangle(4);
    }


    public static void printTriangle(int size) {
        int numSize = 0;
        while (numSize < size) {
            printStars(numSize);
            numSize++;
        }
    }

    public static void printStars(int number) {
        int numStar = 0;
        while (numStar <= number) {
            System.out.print("*");
            numStar++;
        }
        System.out.println();
    }
}

Once we started adding spaces in, I totally got lost and have no idea how to call what and when. I don't know how to properly call the space method into the triangle method as they are asking.

farmac :

This should do the job.

public static void printTriangle(int size) {
    int numSize = 0;
    while (numSize < size) {
        printSpaces(size - numSize - 1);
        printStars(numSize);
        numSize++;
    }
}
public static void printSpaces(int number) {
    int numSpaces = 0;
    while (numSpaces < number) {
        System.out.print(" ");
        numSpaces++;
    }
}
    public static void printStars(int number) {
        int numStar = 0;
        while (numStar <= number) {
            System.out.print("*");
            numStar++;
        }
        System.out.println();
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=27089&siteId=1