简体   繁体   English

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

[英]Get input from user and print decreasing pattern of numbers java

Can someone help me write a code that prints the following pattern. 有人可以帮我写一个打印以下模式的代码吗?

987654321
 98765432
  9876543
   987654
    98765
     9876
      987
       98
        9          

This is my code sample but I am getting the exact opposite of the above pattern. 这是我的代码示例,但与上述模式完全相反。

        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--;
            }

Thanks in advance!! 提前致谢!!

I would start with an initial value of 987654321 in a StringBuilder , then loop while that contains characters; 我将从StringBuilder的初始值987654321开始,然后在包含字符的情况下循环; in every iteration of the loop, we want to print the difference (in spaces) between the initial length (nine) and the current length of the StringBuilder , then print the contents of the StringBuilder before removing the last character. 在循环的每次迭代,我们要打印的差(空间)的初始长度(9张),在当前长度之间StringBuilder ,然后打印的内容StringBuilder删除最后一个字符之前。 Like, 喜欢,

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);
}

Which outputs (as requested) 哪些输出(根据要求)

987654321
 98765432
  9876543
   987654
    98765
     9876
      987
       98
        9

I'll leave filling the initial StringBuilder and adjusting nine into a variable as an exercise for the reader. 我将填写初始的StringBuilder并将九个变量调整为一个变量,以供读者练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM