java - 如何编写一个输出三角形数字的java程序?

标签 java for-loop nested

我知道有一篇与此类似的帖子,但根据答案,我无法将答案应用于我当前的类(class),也无法理解其余答案。

我需要使用嵌套的“for 循环”创建一个程序,该程序创建像这样的输出(只是对称的)。我已经花了整整两个晚上的时间试图让它工作,但无法弄清楚......

               1 
             1 2 1 
            1 2 4 2 1 
          1 2 4 8 4 2 1 
        1 2 4 8 16 8 4 2 1 
      1 2 4 8 16 32 16 8 4 2 1 
   1 2 4 8 16 32 64 32 16 8 4 2 1 
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1 

我将非常感谢任何帮助!!!

public class PyramidOfDoom { 
    public static void main(String[] args) 
        int k = 2; 
        int totalWidth = 8; 
        for (int row = 1; row <= totalWidth; row++) { 
            for (int col = 1; col <= totalWidth; col++) { 
                if (col <= totalWidth - row) { 
                    System.out.print(" "); 
                } else { 
                    System.out.print(k);; 
                } 
            } 
            System.out.println(); 
        } 
    } 
}

最佳答案

我认为可以通过简单的步骤来完成: 1. 打印前导空格 2. 打印递增数字 3. 打印递减数字 4. 打印尾随空格 5 打印新行。

示例代码(概念)如下。

    int row = 10;
    for(int i=1; i<=numRow ; i++){
       int num = 1;
       for(int j=0; j<numRow- i; j++ ){
           System.out.print("   ");
       }
       for(int j=numRow-i+1; j<=numRow ; j++ ){
           System.out.print(num+" ");
           num=num*2;
       }
       num=num/2;
       for(int j=numRow+1; j<numRow+i; j++ ){
           num=num/2;
           System.out.print(num+" ");
       }
       for(int j=numRow+i+1; j<=numRow*2; j++ ){
           System.out.print("  ");
       }
       System.out.print("\n");
    }

关于java - 如何编写一个输出三角形数字的java程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12830616/

相关文章:

java - Kryo 序列化类型检测

将字符串从 main 复制到结构 c

arrays - 在 Swift 中更新数组中的字符串数量

javascript - AngularJS 嵌套 ng-repeats 和嵌套绑定(bind)

python - 平面样式如何尝试多种方法?

python - pyparsing 中的 python 列表(嵌套)解析器是什么样的?

java - 我遇到了 HTTP 和 HTTPS 协议(protocol)问题

java - 在连接PC的移动设备上读写数据

java - Spring数据 Cassandra : How to query tables with compound keys?

javascript - 为什么我的 'for' 语句循环和其中的 if 语句不执行?