编写一个程序,生成圣诞树图像作为输出。我不知道这是什么错误

时间:2019-04-05 16:35:57

标签: java

我的代码在运行时会导致无限循环。不知道怎么了 !(https://d2vlcm61l7u1fs.cloudfront.net/media%2F1aa%2F1aa1af9f-41ff-48d8-89e9-7b093a909045%2Fphpbrt5Fy.png

我尝试了以下代码。它可以正确编译。

公共课程Project3_1 {

//declare SEGMENTS and HEIGHT
public static final int SEGMENTS = 4;
public static final int HEIGHT = 4;
public static final int TOTAL = (2*(SEGMENTS)) + (2*(HEIGHT)) - 3;

public static void TopTree(int SEGMENTS, int HEIGHT) {


    for (int s = 1; s <= SEGMENTS; s++) {

        for (int h = 1; h <= HEIGHT; h++) {

            int ASTERISKS = ((2*s) + (2*h) - 3);
            int SPACES = ((TOTAL - ASTERISKS)/2);

            //spaces
            for (int b = 1; b <= SPACES; b++) {
                System.out.print(" ");
            }

            //Asterisks
            for (int a = 1; a <= ASTERISKS; a++) {
                System.out.print("*");
            }

            System.out.println();

        }
    }
}

public static void TreeBase() {

    int x = (TOTAL - 7)/2;

    for (int i = 1; i <= (TOTAL-1)/2; i++){
        System.out.print(" ");
    }
    System.out.println("*");

    for (int i = 1; i <= (TOTAL-1)/2; i++){
        System.out.print(" ");
    }
    System.out.println("*");

    for (int i = 1; i <= x; x++){
        System.out.print(" ");
    }
    for (int i = 1; i <= 7; i++) {
        System.out.print("*");
    }
    for (int i = 1; i <= (TOTAL - (x + 7)); i++) {
        System.out.print(" ");
    }
    System.out.println("");
}

public static void main (String[] args){
    TopTree(SEGMENTS, HEIGHT);
    TreeBase();
}

}

1 个答案:

答案 0 :(得分:0)

在TreeBase()中检查第三个循环,您增加了错误的变量。您发布的代码对我来说运行良好,由于我提到的那个循环不正确,因此它不会使星号的底线变暗。解决该问题后,您应该会很好