简体   繁体   中英

How to print star pattern in java?

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();
    }
}

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();
}

Try this one. you have to declare new variable "count = 0" and iterate by 2 in outer loop.

public static void main(String[] args) {
    int count = 1;
    for(int i = 0; i < 6; i++){
        for(int j =0 ; j<13; j++){
            if(count==j){
                System.out.print(" - ");
            }
            else
                System.out.print("*");
        }
        count = count+2;
        System.out.println("");
    }
}

Output :

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

What about a very simple approach: just shift original string 2 positions right:

public static void printStarPattern() {
    String str = "* - ***********";
    int length = str.length();
    int offs = 2;

    for (int row = 0; row < 6; row++) {
        System.out.println(str);
        // rotate string to 'offs' positions right
        str = str.substring(str.length() - offs) + str.substring(0, length - offs);
    }
}
public class RectangleHyphen {
public static void main(String[] args) {
    for (int i = 0, c =1; i < 6; i++,c+=2) {
        for (int j = 0; j < 14; j++) {
          if (j==c) {
              System.out.print("_");
          }else
              System.out.print("*");
        }
        System.out.println();
    }
}

}

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