我正在学习在线 Java 类(class),我的任务是创建一棵圣诞树,该圣诞树可以根据确定树高度的用户输入来形成。我无法在打印圣诞树的方法中打印任何内容。我只能调用其他方法来为我进行打印。输入只是树本身的高度,而不是底部。无论高度如何,底座的尺寸都是相同的。
我尝试了多种不同的选项来获得所需的结果,但以下代码是我最接近的。结果是树的弯曲版本,但它很接近......我只是不知道我做错了什么。
public static void printStars(int amount) {
int i = 0;
while (i < amount) {
System.out.print("*");
i++;
}
System.out.println("");
}
public static void printWhitespaces(int amount) {
int i = 0;
while (i < amount) {
System.out.print(" ");
i++;
}
}
public static void xmasTree(int height) {
int i = 1; // Stars incrementer
while (i <= height) {
int s = (height - i) / 2;
printWhitespaces(s);
printStars(i);
i++;
}
}
结果:
*
**
***
****
*****
******
*******
********
*********
**********
Desired result:
*
***
*****
*******
***
***
最佳答案
我没有运行这个,但希望它没问题;)
public static void printStars(int amount) {
while (--amount >= 0)
System.out.print("*");
System.out.println("");
}
public static void printWhitespaces(int amount) {
while (--amount >= 0)
System.out.print(" ");
}
public static void xmasTree(int height) {
int i = 1; // Stars incrementer
// crown
while (i <= height) {
printWhitespaces(height - i);
printStars(2*i-1);
i++;
}
// trunk
i = 2;
while (--i>=0) {
printWhitespaces(height - 2);
printStars(3);
}
}
关于java - 仅使用 while 循环创建圣诞树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29115757/