-4

我有这个倒金字塔:

     String spaces = "";

         int x =0;
             int counter = fulllName.length();

         for( x = 0; x < fullName.length()/2; x++ ) 
         {
             System.out.println(counter-x + "[" + spaces + fullName.substring(x, fullName.length()-x) + "]");
             spaces = spaces + " ";
         }

我想让它在每行的开头打印每行的长度,但作为金字塔本身的一部分。我还想将每一行括在括号 [ ] 中,但行的长度在括号之外。当我尝试时,它会打印如下:

     7[ 1111111]
     7[  11111]
     7[   111]
     7[    1]

我想要这样的东西:

    7[1111111]
     5[11111]
      3[111]
       1[1]
        0[]
4

4 回答 4

2

只需在打印语句中替换counter-x + "[" + spaces为。spaces + counter-x + "["

于 2012-10-02T14:54:48.440 回答
1

不应该是:

spaces + fullName.length()-x + "[" + fullName.substring(x, fullName.length()-x + "]"
于 2012-10-02T14:54:00.187 回答
1

改变

for( x = 0; x < fullName.length()/2; x++ ) 
{
     System.out.println(counter-x + "[" + spaces + fullName.substring(x, fullName.length()-x) + "]");
     spaces = spaces + " ";
}

for( x = 0; x < fullName.length()/2; x++ ) 
{
   System.out.println(spaces + counter-x + "[" + fullName.substring(x, full Name.length()-x) + "]");
   spaces = spaces + " ";
}
于 2012-10-02T14:55:45.490 回答
1

你在括号中有空格,你的 println() 应该是:

System.out.println(spaces + (counter - x) + "[" + fullName.substring(x, fullName.length() - x) + "]");
于 2012-10-02T14:59:53.687 回答