簡體   English   中英

在 ASCII 菱形 Java 內插入字符串 Label

[英]Insert String Label Inside ASCII Diamond Shape Java

我畫了一個帶有 ASCII 字符(所有“*”)的菱形,我試圖在形狀內得到一個 label 或單詞。 我已經用三角形和正方形等其他形狀完成了這個概念。所以我的算法有高度參數,他們希望 label 出現在什么形狀的線條上,然后是字符串 label 本身(不關心掃描儀對於用戶輸入,我在另一堂課上得到了)。 我發現如果我將 i 設置為 label 高度,然后當該循環完成打印 label 時(仍在試圖弄清楚如何讓它在形狀中居中)。

public static void drawDiamond(int height, int labelHeight, String label)
{
    int halfHeight = height / 2;
    for (int row = 0; row < labelHeight; row++) {
        for (int column = 0; column < height; column++) {
            if ((column == Math.abs(row - halfHeight))
                    || (column == (row + halfHeight))
                    || (column == (height - row + halfHeight - 1))) {
                System.out.print("*");
            } else {
                System.out.print(" ");
            }
        }
        System.out.println();
    }
    System.out.println(label);
}

預期結果的圖片

但我的具體問題是在打印 label 后繼續構建鑽石。 也許更好的選擇是打印整個三角形,然后在正確的行中替換 label,但由於它不是一個令人頭疼的字符串。 對不起,這很長。 有什么想法嗎?

編輯:在行迭代器達到 label 高度然后打印 label 之后,我包含了一個額外的循環。 所以我得到了一些形狀接近的東西(除了小費哈哈)。 但現在我的問題變成了讓 label 在形狀中居中。 我不能通過添加帶有星號的打印空間來強制它,因為大小會根據用戶輸入而改變。 我可以嘗試訪問前一行有字符的位置,或者僅憑借菱形的形狀確定中心,然后以某種方式相應地放置 label。

您可以使用heightlabelheight來確定text開始處的 position。 X or vertical position 將是labelheight/2 讓我通過一個例子來解釋如何獲得 position Y or horizontal

假設我們要將文本居中到下一行的中心。

----------------
     sample 
     |
This position will be ( length of line / 2 ) - (length of text / 2). Because if we place text 
in the center, half the length of the text will be on the left side, subtracting that will 
give us the left position where our text should start.

首先,在for循環之前獲取xPosyPos

int xPosWord = labelHeight / 2;
int yPosWord = (height) / 2 - (label.length() / 2);

然后在for循環中檢查是否應該使用rowcolumn索引打印文本。

if (row == xPosWord) {
    if (column >= yPosWord && column < yPosWord + label.length()) {
        System.out.print(label.charAt(column - yPosWord));
        continue;
    }
}

示例 output 用於drawDiamond(15, 15, "Sample Text")

       *       
      * *      
     *   *     
    *     *    
   *       *   
  *         *  
 *           * 
* Sample Text *
 *           * 
  *         *  
   *       *   
    *     *    
     *   *     
      * *      
       *  

上述方法適用於長度不超過菱形寬度的文本。

暫無
暫無

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

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