从用户获取输入并打印数字的递减模式

时间:2018-12-02 18:26:33

标签: java taphold

有人可以帮我写出打印以下图案的代码吗?

987654321
 98765432
  9876543
   987654
    98765
     9876
      987
       98
        9          

这是我的代码示例,但与上述模式完全相反。

        height = getInPut("Enter the height of the triangle");
        int h = Integer.parseInt(height);
        int start = h, num=1,max=h;

        for (int r= 1; r <=h; r++)
        {
            System.out.println();
            for (int j = 1; j<= max; j++)
            {
                if(h>=6 && h<=10) 
                {
                    System.out.print(num);  
               }else{
                   System.out.println("height should be between 6-10");
                   System.exit(0);
               }

              num++;
            }
           num= r+1;
           max--;
            }

提前谢谢!

1 个答案:

答案 0 :(得分:0)

我将从987654321的初始值StringBuilder开始,然后在包含字符的循环中循环;在循环的每次迭代中,我们要打印StringBuilder的初始长度(九)和当前长度之间的差(以空格为单位),然后打印StringBuilder的内容,然后再删除最后一个字符。喜欢,

StringBuilder sb = new StringBuilder("987654321");
while (sb.length() > 0) {
    for (int i = 0; i < 9 - sb.length(); i++) {
        System.out.print(' ');
    }
    System.out.println(sb);
    sb.setLength(sb.length() - 1);
}

哪些输出(按要求)

987654321
 98765432
  9876543
   987654
    98765
     9876
      987
       98
        9

我将保留填写开头的StringBuilder并将9调整为变量,以供读者练习。

相关问题