用数字作为行打印的三角形

时间:2013-12-25 23:55:36

标签: java for-loop

我有一个任务要求我们创建一个看起来像这样的三角形,只有for循环,我目前无法将我的星号变成那些我可以将整个三角形变成数字的数字。

enter image description here

这是打印三角形的代码:

 public class ExtraCredit_Bazar {

    public static void main ( String arg[] ){

       for (int i=1; i<10; i += 2)
       {
            for (int k=0; k < (4 - i / 2); k++)
            {
                 System.out.print(" ");
            }
            for (int j=0; j<i; j++)
            {
                    System.out.print("*");
            }
            System.out.println("");

       }
  }

3 个答案:

答案 0 :(得分:0)

像这样编辑你的第二个内循环:

int number = 1;

for (int j = 0; j < i; j++) {
    System.out.print(number);

    if (j < i / 2) {
        number *= 2;
    } else {
        number /= 2;
    }
}

答案 1 :(得分:0)

据我了解,您不知道如何为每个级别获取正确的数字。你可以这样做:

public class ExtraCredit_Bazar {

    public static void main ( String arg[] ){

       for (int i=1; i<10; i += 2){
            for (int k=0; k < (4 - i / 2); k++){
                 System.out.print(" ");
            }
            int number = 1;
            for (int j=0; j < (i/2); j++){
                System.out.print(number);
                number *= 2;
            }
            for (int j= (i/2); j < i; j++){
                System.out.print(number);
                number /= 2;
            }
            System.out.println("");
        }
    }
}

所以基本上,我将你的for循环打印'*'分成两个for循环。第一个打印一个数字并将其乘以2以进行下一次迭代。然后,当到达中间时,第二个循环进入,它将数字除以2再次变小。

答案 2 :(得分:0)

中间的数字应该很容易获得。对于其余的数字,我建议在打印之前将字符串保存到数组中,以便根据最长(最后)字符串的长度使字符串居中。

public class ExtraCredit_Bazar {

    public static void main ( String arg[] ) {
       int z = 1;
       final int lineCount = 8;
       String[] lines = new String[lineCount];
       // do first iteration "by hand" 
       String left="1";
       String right="1";
       lines[0] = left;

       for (int i=1; i<lineCount ; i++)
       {
            // update z here

            // update left here

            lines[i] = /*concat strings here (left, right and maybe spaces)*/;

            // update right here Integer.toString(int) if necessary
       }

       final int maxStringLength = lines[lineCount-1].length();
       for (int i = lineCount-2; i >= 0; i--) {
           // add spaces to the left of lines[i] dependent on it's
           // length and maxStringLength

           // if you do it right, you can reuse the spaces you add to the
           // left and don't have to create them from the start.
           // Therefore the "backwards iteration". 
       }

       // print the lines
}

您可能已经注意到缺少代码。如果您了解java(和数学)的基础知识,您应该能够轻松地解决这个问题。