How to print star pattern in java?

Kieron hong :

how to print following star pattern using java?

* - ***********
*** - *********
***** - *******
******* - *****
********* - ***
*********** - *

I'm new in java and I have try to print the rectangle loop but how to print the - inside the rectangle?

public static void main(String[] args) {
    for (int i = 0; i < 6; i++)
    {
        for (int j = 0; j <= 14; j++)
        {
            System.out.print("*");
        }
        System.out.println();
    }
}
user7 :

The hyphens are printed after an odd number of stars.

After one star in line one.

After three stars in line two.

After five stars in line three.

and so on..

We can find when to print hyphen from the outer loop variable i.

Hence, you can see if the value of j is equal to 2i and print hyphen if true.

for (int i = 0; i < 6; i++)
{
    for (int j = 0; j <= 11; j++)
    {
        System.out.print("*");
        if (j == i * 2) {
            System.out.print(" - ");
        }
    }
    System.out.println();
}

Guess you like

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