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