Java Examples – Printing a Diamond Shape

Java 实例Java Examples

Output a diamond shape with a specified number of lines.

Example

public class Diamond { public static void main(String[] args) { print(8); //Output an 8-line diamond } public static void print(int size) { if (size % 2 == 0) { size++; //Calculate the size of the diamond } for (int i = 0; i < size / 2 + 1; i++) { for (int j = size / 2 + 1; j > i + 1; j--) { System.out.print(" "); //Output blank spaces at the top-left corner } for (int j = 0; j < 2 * i + 1; j++) { System.out.print("*"); //Output the upper half edge of the diamond } System.out.println(); //New line } for (int i = size / 2 + 1; i < size; i++) { for (int j = 0; j < i - size / 2; j++) { System.out.print(" "); //Output blank spaces at the bottom-left corner of the diamond } for (int j = 0; j < 2 * size - 1 - 2 * i; j++) { System.out.print("*"); //Output the lower half edge of the diamond } System.out.println(); //New line } } }

Output result:

   *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

Java 实例Java Examples

Other extensions