使用循环输出ASCII菱形



我正试图用Java编写一个程序,从用户那里捕获一个整数(假设数据有效(,然后根据整数的大小输出一个菱形,即用户输入5,输出为:

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

到目前为止,我有:

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

只输出:

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

我想降低h的值,但这只会产生钻石的左手边。

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

好吧,这就是代码,但当我看到S.L.Barth的评论时,我才意识到这是一个家庭作业。因此,我强烈建议您在将其用作最终版本之前,先了解此代码中所写的内容。请随时提出任何问题!

看看你的情况:

if (i != h)

这仅着眼于列编号i和中间点h。您需要一个查看列编号和行编号的条件。更准确地说,您需要一个条件来查看列编号、行编号以及列编号与中间点的距离
由于这是一个家庭作业问题,我把确定确切的公式留给你,但如果你需要的话,我愿意再提供一些提示。祝你好运

您可以使用从-hh的两个嵌套for循环,其中h是半个菱形。钻石的边缘是在以下情况下获得的:

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

如果用户输入n=5,然后输入h=2,则菱形如下所示:

n=5, h=2
--*--
-*-*-
*---*
-*-*-
--*--

在线试用!

// user input
int n = 9;
// half a diamond
int h = n / 2;
// output a diamond shape
System.out.println("n=" + n + ", h=" + h);
for (int i = -h; i <= h; i++) {
    for (int j = -h; j <= h; j++) {
        if (Math.abs(i) + Math.abs(j) == h) {
            System.out.print("*");
        } else {
            System.out.print("-");
        }
    }
    System.out.println();
}

输出:

n=9, h=4
----*----
---*-*---
--*---*--
-*-----*-
*-------*
-*-----*-
--*---*--
---*-*---
----*----

最新更新