java - 嵌套循环使字符居中

标签 java for-loop nested-loops

我正在尝试制作一棵树,如下所示:

  *
 ***
*****
 ===

我能够使树居中,但我似乎无法使树桩与树的其余部分居中。我不知道如何做到这一点,任何帮助将不胜感激! (树桩总是有三个等号)

        int height = 4;
        int counter = 1;
        int spaces = 20;
        for (int row = 1; row <= height; row++){

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

           for (int j = 1; j <= counter; j++){
              System.out.print("*");     
           }

           System.out.println("");
           counter += 2;
           spaces--;


         } // end of outer loop
         for(int i=0; i<3; i++){
            System.out.print("=");
         }

最佳答案

public class A {

    public static void main(String[] args) {

        int height = Integer.parseInt(args[0]);
        int counter = 1;
        int spaces = height-1;
        for (int row = 1; row <= height; row++){

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

           for (int j = 1; j <= counter; j++){
              System.out.print("*");
           }

           System.out.println("");
           counter += 2;
           spaces--;
         } // end of outer loop
         counter-=2; // length of last line
         for(int i=1; i<=counter/2-1; i++){
            System.out.print(" ");
          }
          System.out.print("===");
    }
}

观察到我们在第一行留下了等于(最后一行的长度)/2的空间,并且它不断减少1。我们可以通过算术级数找到最后一行的长度。

请注意 === 的中间 = 始终位于(最后一行的长度)/2+1 个字符上。因此我们必须在其前面添加空格直到两个字符,即(长度)/2-1。

关于java - 嵌套循环使字符居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23625196/

相关文章:

Python:使用for循环输出ASCII表

c - 尝试用 C 语言编写输出棋盘格的代码

java - 为什么我们不能从 actionPerformed() 中得到 'throws' 异常

java - 是否有理由使用字符串 => 索引到 vector 的映射,而不是字符串 => 对象?

Java for循环的几个条件

带有生成器的 Python 嵌套循环不起作用(在某些情况下)?

c - 如何跳出嵌套循环?

javascript - 当我更改另一个数组中的值时,数组中的值会更改吗?

java.lang.IllegalStateException : org. hibernate .TransientPropertyValueException

java - 如何在 Android API <24 中将对象包装在 lambda 中