我似乎无法将圣诞树的树干和底座分开。树干和底座是固定值,对于为树叶指定的任何值,它们必须居中。
我尝试这样做
public class Proj01_xmasTree {
//christmas time scott r portdog45680-41fasda
public static void main(String args[]) {
//int gives amount of lines to print
int size = 4;
int treeWidth = size * 2 - 1;
tree1(size);
tree2(size);
tree3(size);
trunk(1);
base(1);
}
public static void tree1(int size){
// "i" starts on different stars
for (int i = 0; i < size; i++){
//4 + 1 + 0 = 5. 4 + 1 - 1 = 4, etc..
for (int j = 0; j < size + 1 - i; j++)
System.out.print(" ");
//stars 1,3,5,7. i*2 + 1. 0 + 1 = 1.
for (int k = 0; k < i*2 + 1; k++){
System.out.print("*");
}
System.out.println();
}
}
public static void tree2(int size){
//"i" starts on different stars
for (int i = 1; i < size; i++){
//4 + 1 + 0 = 5. 4 + 1 - 1 = 4, etc..
for (int j = 0; j < size + 1 - i; j++)
System.out.print(" ");
//stars 1,3,5,7. i*2 + 1. 0 + 1 = 1.
for (int k = 0; k < i*2 + 1; k++){
System.out.print("*");
}
System.out.println();
}
}
public static void tree3(int size){
//"i" starts on different stars
for (int i = 2; i <= size; i++){
//4 + 1 + 0 = 5. 4 + 1 - 1 = 4, etc..
for (int j = 0; j < size + 1 - i; j++)
System.out.print(" ");
//stars 5,7,9,12
for (int k = 0; k < i*2 + 1; k++){
System.out.print("*");
}
System.out.println();
}
}
public static void trunk(int treeWidth){
int spacing = (treeWidth - 2) / 2;
for (int i = 0; i < 2; i++){
for (int j = 0; j < spacing; j++){
System.out.print(" ");
}
System.out.println("*");
}
}
public static void base(int size){
for (int i = 0; i < 1; i++){
for (int j = 0; j < size/2; j++){
System.out.print(" ");
}
for (int k = 0; k < 3; k++){
System.out.print("*");
}
}
}
}
哪个输出:
*
***
*****
*******
***
*****
*******
*****
*******
*********
*
*
***
所需输出:
*
***
*****
*******
***
*****
*******
*****
*******
*********
*
*
***
(注意:树干和底座是分开的方法。它们必须像任何叶子一样固定,请记住这一点。)
我已更新了
trunk
和 base
功能,如下(tree1
、tree2
和 tree3
功能未更改)。
private static void trunk(int size) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j <= size; j++) {
System.out.print(" ");
}
System.out.println("*");
}
}
private static void base(int size) {
for (int j = 0; j < size; j++) {
System.out.print(" ");
}
for (int k = 0; k < 3; k++) {
System.out.print("*");
}
}
对于
trunk
函数,所需的初始空格数与 size + 1
的值相同,对于基数,则为 size
。
现在所有功能仅基于
size
参数工作
int size = 4;
tree1(size);
tree2(size);
tree3(size);
trunk(size);
base(size);