简体   繁体   中英

Printing Right-Aligned Triangle by Calling Methods

Good day! Newbie in Java Programming. Would like to ask for some help on understanding the looping. The program's aim is to print a right-aligned triangle. I've created method for printing "*" and another one for " " (whitespace). I'm having trouble understanding on how can I implement the whitespace in my main method. Thank you!

Expected output:

"printTriangle(4);"

     *
    **
   ***
  ****

Here is my code:

public class PrintingLikeBoss {

public static void printStars(int amount) {
    int i = 1;

    while (i <= amount) {
        System.out.print("*");
        i++;
    }
    System.out.println("");
}

public static void printWhitespaces(int amount) {
    int i = 1;

    while (i <= amount) {
        System.out.print(" ");
        i++;
   }
    System.out.println("");
}

public static void printTriangle(int size) {

    int i = 1;
    int j = 1;
    while (i >= 0) {
        printStars(size);
        i++;
        }
    }


    printTriangle(4);
    }
}

The printTriangle() methode will never end due to i always being greater then 0.

Also there is no main method in your code, therefore you will not be able to run it.

Now for the answer to your question:

   public static void printTriangle(int size){
        int i = size;
        int j = 1;
        while(j<=i){
            printWhite(i-j);
            printStar(j);
            j++;
            System.out.println("");
        }
    }

    public static void printWhite(int size){
        int i = size;
        for(int j = 0; j<i; j++){
            System.out.print(" ");
        }
    }

    public static void printStar(int size){
        int i = size;
        for(int j = 0; j<i; j++){
            System.out.print("*");
        }

    }

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

This should provide you an output like this:

     *
    **
   ***
  ****

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM