Question

I am trying to write a program in Java that captures an integer from the user (assume data is valid) and then outputs a diamond shape depending on the size of the integer, i.e. User enters 5, output would be:

--*--
-*-*-
*---*
-*-*-
--*--

So far I have:

if ( sqr < 0 ) {
        // Negative
        System.out.print("#Sides of square must be positive");
    }

    if ( sqr % 2 == 0 ) {
        // Even
        System.out.print("#Size (" + sqr + ") invalid must be odd");
    } else {
        // Odd
        h = ( sqr - 1 ) / 2; // Calculates the halfway point of the square
        // System.out.println();
        for ( j=0;j<sqr;j++ ) {    

            for (i=0;i<sqr;i++) {

                if ( i != h) {
                    System.out.print(x);
                } else {
                    System.out.print(y);
                }

            }

            System.out.println();
        }

    }

Which just outputs

--*--
--*--
--*--
--*--
--*--

Any ideas, I was thinking about decreasing the value of h but that would only produce the left hand side of the diamond.

Was it helpful?

Solution

void Draw(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();
            }
        }

Ok, now this is the code, but as I saw S.L. Barth's comment I just realised this is a homework. So I strongly encourage you to understand what is written in this code before using it as final. Feel free to ask any questions!

OTHER TIPS

Take a look at your condition:

 if ( i != h )

This only looks at the column number (i) and the midway point (h). You need a condition that looks at the column number and the row number. More precisely, you need a condition that looks at the column number, the row number, and the distance of the column number from the midway point.
Since this is a homework question, I leave determining the precise formula to you, but I'm willing to drop some more hints if you need them. Good luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top