题解 | #圣诞树#
圣诞树
https://www.nowcoder.com/practice/9a03096ed8ab449e9b10b0466de29eb2
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int h = scan.nextInt(); //高度
//打印树叶
for (int i = 0; i < h * 3; i++) {
//(1)打印空位
for (int j = 0; j < (h * 3 - 1 - i); j++) {
System.out.print(" ");
}
//(2)打印叶子
for (int z = 0; z < (i + 1); z++) {
// z是每层所的叶子数 例如:第一层1 第二层2
if (i % 3 == 0) {
//如果为每次第三层的下面第一层 就进入if
if (z % 3 == 0) {
//找出规律 比如第七层时,0、3、6是* 注意i是层数不过i是从0开始
System.out.print("* ");
} else {
System.out.print(" ");//两个空位
}
} else if(i % 3 == 1) {
//如果为每次第三层的下面第两层 就进入if
if ((z + 1) % 3 == 0) {
//第八层时,3、6时空位,但是需要+1 不然2、5才是空位
System.out.print(" ");
} else {
System.out.print("* ");
}
} else {
System.out.print("* ");
}
}
//(3)换行,开始下一层的叶子
System.out.println();
}
//打印树干
for (int i = 0; i < h; i++) {
for (int j = 0; j < (h * 3 - 1); j++) {
System.out.print(" ");
}
System.out.println("*");
}
}
}Java基础练习题 文章被收录于专栏
都是一些基础的语法题目,每天可以刷几道。
