【发布时间】:2016-10-22 04:53:26
【问题描述】:
我正在尝试用用户输入的三角形顶部和矩形底座构建一棵圣诞树,但我目前在构建底座时遇到了困难。规格如下:三角形以单个*开头,每行增加*的数量,每行总共增加2,这样最后一行是2(n)-1,n是输入的高度三角形。树下的矩形(树桩)的高度等于 1 加上 (1/5)n,树桩的宽度是 1/3n,但是如果 1/3n 的结果是偶数,则在总数中加 1树桩宽度。 (即树桩宽度总是奇数。) 到目前为止,这是我所拥有的,树的三角形部分很好,但矩形是一团糟。
public class xmasTree {
public static final int TREE_MAXIMUM = 20;
public static final int TREE_MINIMUM = 3;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
//User introduction
System.out.println("This program prints a \"Christmas\" tree. You "
+ "choose how big the tree will be (within reason);
// prompt for and get user input
System.out.println("How tall should the top of the tree be?");
int treeHeight = keyboard.nextInt();
while (treeHeight < TREE_MINIMUM || TREE_MAXIMUM < treeHeight) {
System.out.println("That's not a valid size. I can only do trees "
+ "from 3 to 20.");
System.out.println("Qutting now.");
System.exit(0);
}
//Print the top triangle section of the christmas tree
for (int i = 0; i < treeHeight; i++) {
for (int j = 0; j < treeHeight - i; j++) {
System.out.print(" ");
}
for (int k = 0; k < (2 * i + 1); k++) {
System.out.print("*");
}
System.out.println();
}
//Print the bottom rectangle section of the tree
for (int c = 0; c <= (1 + (treeHeight / 5)); c++) {
for (int d = 0; d <= (treeHeight / 3); d++) {
System.out.print("");
}
System.out.printf("*");
}
}
}
如果有人可以帮助我弄清楚如何为矩形获得正确的输入形状,那将是很棒的,我知道一旦正确构建,我可以使用简单的 printf 将其居中。
【问题讨论】:
-
可以添加输出吗?
-
你希望
print("")做什么?