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++;
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP