Java 程式,用於列印菱形


可以透過列印一個三角形,然後列印一個倒放的三角形來列印菱形。以下示例對此作了說明 −

*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*

一個演示此過程的程式如下。

示例

 線上演示

public class Example {
   public static void main(String[] args) {
      int n = 6;
      int s = n - 1;
      System.out.print("A diamond with " + 2*n + " rows is as follows:

");       for (int i = 0; i < n; i++) {          for (int j = 0; j < s; j++)          System.out.print(" ");          for (int j = 0; j <= i; j++)          System.out.print("* ");          System.out.print("
");          s--;       }       s = 0;       for (int i = n; i > 0; i--) {          for (int j = 0; j < s; j++)          System.out.print(" ");          for (int j = 0; j < i; j++)          System.out.print("* ");          System.out.print("
");          s++;       }    } }

輸出

A diamond with 12 rows is as follows:

*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*

現在,讓我們來理解一下以上程式。

菱形是透過列印一個三角形然後列印一個倒置三角形來建立的。這是透過使用巢狀 for 迴圈來完成的。上三角形的程式碼段如下。

int n = 6;
int s = n - 1;
System.out.print("A diamond with " + 2*n + " rows is as follows:

"); for (int i = 0; i < n; i++) {    for (int j = 0; j < s; j++)    System.out.print(" ");    for (int j = 0; j <= i; j++)    System.out.print("* ");    System.out.print("
");    s--; }

下三角形的程式碼段如下。

s = 0;
for (int i = n; i > 0; i--) {
   for (int j = 0; j < s; j++)
   System.out.print(" ");
   for (int j = 0; j < i; j++)
   System.out.print("* ");
   System.out.print("
");    s++; }

更新於: 25-Jun-2020

220 次瀏覽

開啟你的 職業

透過完成課程獲取認證

開始學習
廣告
© . All rights reserved.