Firat
Firat

Reputation: 356

Print a diamond shape with Java

I want to print a grid shape on the output console in Eclipse.

Example Diamond Shapes

Basically I took an integer from user that is the number of stars in a single border of the grid.

Here the code I have up to now:

public class PrintDiamond {
    public static void main(String[] args) {
        System.out.print("Enter the number: ");
        Scanner scan = new Scanner(System.in);
        int num = scan.nextInt();
        num--;
        for (int i = num; i > 0; --i) {
            //Insert spaces in order to center the diamond
            for (int n = 0; n < i; ++n) {
                System.out.print("  ");
            }
            System.out.print(" *");
            for (int n = i; n < num; ++n) {
                System.out.print(" + ");
                System.out.print(" ");
            }//Ending bracket of nested for-loop
            System.out.println();
        }//Ending bracket of for loop
        //Print out a diamond shape based on user input
        for (int i = 0; i <= num; ++i) {//<= to print the last asterisk
            //Insert spaces in order to center the diamond
            for (int n = 0; n < i; ++n) {
                System.out.print("  ");
            }
            System.out.print(" *");
            for (int n = i; n < num; ++n) {
                System.out.print(" + ");
                System.out.print(" ");
            }//Ending bracket of nested for-loop
            System.out.println();
        }//Ending bracket of for loop
    }
}

and the output is (for int. 6):

           *
         * +  
       * +   +  
     * +   +   +  
   * +   +   +   +  
 * +   +   +   +   +  
   * +   +   +   +  
     * +   +   +  
       * +   +  
         * +  
           *

Upvotes: 2

Views: 4146

Answers (4)

user16314724
user16314724

Reputation:

Two nested for loops from -n to n and one if else statement. The zero point is in the center of a diamond, and the boundary is obtained when:

Math.abs(i) + Math.abs(j) == n

Try it online!

public static void main(String[] args) {
    printDiamond(0);
    printDiamond(2);
    printDiamond(5);
}

static void printDiamond(int n) {
    System.out.println("n=" + n);
    for (int i = -n; i <= n; i++) {
        for (int j = -n; j <= n; j++)
            if (Math.abs(i) + Math.abs(j) == n)
                System.out.print("*  ");
            else if (Math.abs(i) + Math.abs(j) < n && j % 2 == 0)
                System.out.print("+  ");
            else
                System.out.print("   ");
        System.out.println();
    }
}

Output (combined):

n=0 n=2 n=5
*  










      *        
* + *
* + *
* + *
*






               *                 
* + *
* + *
* + + + *
* + + + *
* + + + + + *
* + + + *
* + + + *
* + *
* + *
*

See also: Print an ASCII diamond of asterisks

Upvotes: 0

Vladimir Petrakovich
Vladimir Petrakovich

Reputation: 4286

Here is the code:

public static void main(String[] args) {
    System.out.print("Enter the number: ");
    Scanner scan = new Scanner(System.in);
    int num = scan.nextInt();
    final char[][] diamond = makeDiamond(num);
    for (int i = 0; i < diamond.length; i++) {
        for (int j = 0; j < diamond[i].length; j++) {
            System.out.print(diamond[i][j]);
        }
        System.out.println();
    }
}

public static char[][] makeDiamond(int n) {
    int width = 1 + 4 * (n - 1);
    int height = 1 + 2 * (n - 1);
    char[][] out = new char[height][width];
    int x0 = 2 * (n - 1);
    int y0 = n - 1;
    for (int i = 0; i < width; i += 2) {
        // Top borders
        int y1 = Math.abs(y0 - i / 2);
        out[y1][i] = '*';

        // Bottom borders
        int y2 = height - Math.abs(i / 2 - y0) - 1;
        out[y2][i] = '*';

        if ((x0 - i) % 4 == 0) {
            // Plus signs
            for (int j = y1 + 1; j < y2; j++) {
                out[j][i] = '+';
            }
        }
    }
    return out;
}

Upvotes: 2

walen
walen

Reputation: 7273

Ok, this looks like a school asignment, so I won't write any code.

First you need to understand and write, in pseudo-code or just plain English, what you want to do:

  • Instructions on how to draw the grid.
    • How many lines should I print?
    • How long is each line?
    • How do I know if I have to print a + or not?
  • General steps of your program.
    • Read size of the grid, N.
    • If N < 1, ask again (or exit program).
    • If N = 1 or greater, print the grid.
  • Detailed sub-steps of your program.
    • Print the grid
      • Loop for number of lines.
      • Create empty array/buffer/list/string with correct length for current line.
      • ...

Because right now, it seems like you haven't figured out any of that. And if that's the case, then your problem has nothing to do with Java but rather with basic programming knowledge, which you won't get if we just code the algorith for you.

Upvotes: 2

Florian Albrecht
Florian Albrecht

Reputation: 2326

Some hints for your solution:

  • Create a method for printing a "diamond row" for a given row width and a given total width of the diamond.
  • Create a tool method for printing a given number of spaces.
  • Your main method should have two simple loops: One for the upper, one for the lower half.
  • The magic is in the method of printing a single diamond row for the given two parameters w and n.

This is always a good approach - reduce your complex problem to a problem with lesser complexity - in this case, by creating methods and using these e.g. in loops.

In your method for printing a single diamond row, you will need to check if you are in an "odd" or "even" row.

Upvotes: 2

Related Questions