java - 仅使用 while 循环创建圣诞树

标签 java loops while-loop

我正在学习在线 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/

相关文章:

c - 为第 4 个字母停止的循环

java - linux下mysql jdbc驱动和Eclipse : ClassNotFoundexception com. mysql.jdbc.Driver

带有 GSON 的 Java 堆空间

ios - 更新 UILabel 看起来像是在浪费性能

c++ - While 在 C++ 中使用定时器循环

Python while 循环语法错误

java - 在 Lotus Notes 9 中运行 Java 代理

java - 在java中使用foreach循环时出现奇怪的错误

java - 如何向用户询问一些问题,然后保存答案并重复询问相同的问题

php - while循环内foreach循环问题