簡體   English   中英

使用循環輸出 ASCII 菱形

[英]Output an ASCII diamond shape using loops

我正在嘗試用 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();
    }
}

好的,現在這是代碼,但是當我看到 SL 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
----*----
---*-*---
--*---*--
-*-----*-
*-------*
-*-----*-
--*---*--
---*-*---
----*----

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM