Java for loop print shape

Question

We would like to use for loop to print shape.

You have to output * one by one using for loop.

**********/*from   w  ww . j  a  v a 2s  .c  o  m*/
*        *
*        *
*        *
*        *
*        *
*        *
*        *
*        *
**********


public class Main {
  public static void main(String[] args) {
    int sides = 10;
    for (int i = 0; i < sides; i++) {
      // first and last rows
      if (i == 0 || i == sides - 1) {
        for (int j = 0; j < sides; j++) {
          System.out.print("*");
        }
      } else {
        System.out.print("*");
        // hollow portion (-2 as 1 * on each side)
        for (int j = 0; j < sides - 2; j++) {
          System.out.print(" ");
        }
        System.out.print("*");
      }
      System.out.println();
    }
  }
}



PreviousNext

Related