Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
306 views
Welcome To Ask or Share your Answers For Others

1 Answer

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...