Printing XYZ in Java using Asterisks

Posted on March 25, 2014 at 23:23 Java

Assumption is that dimension should always be an odd number (you have to be able to have immediately understood why, else please stop reading this this instant). It’s accomplished using brute force, because I just wanted to see it working and prove to myself that I haven’t gone totally rusty yet.

package letter;

public class LetterGenerator {
   public static void main(String[] args) {
      int dim = 7;

      for(int i = 0; i < dim; i++) {
         for(int j = 0; j < dim; j++) {
            if(i == j || i + j == dim - 1) {
               System.out.print("*");
            } else {
               System.out.print(" ");
            }
         }

         System.out.println();
      }

      System.out.println();

      for(int i = 0; i < dim; i++) {
         for(int j = 0; j < dim; j++) {
            if(((i == j || i + j == dim - 1) && i < dim / 2 + 1) || (i > dim / 2 && j == dim / 2)) {
               System.out.print("*");
            } else {
               System.out.print(" ");
            }
         }

         System.out.println();
      }

      System.out.println();

      for(int i = 0; i < dim; i++) {
         for(int j = 0; j < dim; j++) {
            if(i == 0 || i + j == dim - 1 || i == dim - 1) {
               System.out.print("*");
            } else {
               System.out.print(" ");
            }
         }

         System.out.println();
      }
   }
}

Say What?

Name:
E-mail:
Website: (optional)