HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMajor

Print an ASCII diamond

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
diamondprintascii

Problem

This takes a width specified by user and prints a diamond of that width. It uses only three for loops, but could I reduce that further? Is there a more elegant solution?

public class Diamond {

    static boolean cont = true;

    public static void main (String[] args) {
        Scanner input = new Scanner(System.in);
        while (cont) {
            System.out.print("Width: ");
            int width = input.nextInt();
            int lines = width;
            System.out.println();
            for (int line = 0; line < lines; line++) {
                for (int spaces = 0; spaces < Math.abs(line - (lines / 2)); spaces++) {
                    System.out.print(" ");
                }
                for (int marks = 0; marks < width - 2 * (Math.abs(line - (lines / 2))); marks++) {
                    System.out.print("x");
                }       
                System.out.println();
            }
            System.out.println();
        }
    }
}

Solution

There are a few things that we can do to clean this up.

-
This is something I would extract to its own method. Handle getting the user input in the main() method, and then pass that on to the drawDiamond() method.

-
Your for loops are divided into iterating over lines, spaces, and
marks. We can simplify that down to just rows and columns where we can iterate over each individual unit at a time. This will also eliminate one of your System.out.println()s in the final method.

-
We can simplify down the math of where to print a piece of the diamond.

if ((column == Math.abs(row - half)) || (column == (row + half)) || (column == (sqr - row + half - 1)))


Final Method:

void drawDiamond(int sqr)
{
    int half = sqr/2;
    for (int row=0; row<sqr; row++)
    {
        for (int column=0; column<sqr; column++)
        {
            if ((column == Math.abs(row - half)) || (column == (row + half)) || (column == (sqr - row + half - 1)))
            {
                System.out.print("*");
            }
            else System.out.print(" ");
        }
        System.out.println();
    }
}

Code Snippets

if ((column == Math.abs(row - half)) || (column == (row + half)) || (column == (sqr - row + half - 1)))
void drawDiamond(int sqr)
{
    int half = sqr/2;
    for (int row=0; row<sqr; row++)
    {
        for (int column=0; column<sqr; column++)
        {
            if ((column == Math.abs(row - half)) || (column == (row + half)) || (column == (sqr - row + half - 1)))
            {
                System.out.print("*");
            }
            else System.out.print(" ");
        }
        System.out.println();
    }
}

Context

StackExchange Code Review Q#40417, answer score: 27

Revisions (0)

No revisions yet.