输出由"*"构成的棱形
public class Graph {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入一个数:");
int n = sc.nextInt();
//菱形 method 1
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 3 - i; j++)
System.out.print(" ");
for (int j = 0; j < 2 * i + 1; j++)
System.out.print("*");
System.out.println();
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < i + 1; j++)
System.out.print(" ");
for (int j = 0; j < 5 - 2 * i; j++)
System.out.print("*");
System.out.println();
}
棱形输出方法二:调用库中数学方法Math.abs();
//以中心最长的行数为i=0;向上的行数为-1,-2,向下为正号
for (int i = -n; i < n; i++) {
for (int j = 0; j < Math.abs(i) + 1; j++)
System.out.print(" ");
for (int j = 0; j <( n+1) - 2 * Math.abs(i); j++)//调用绝对值函数
System.out.print("*");
System.out.println();
}
运行结果如下:
image.png
image.png
网友评论