用for循环绘制数字

时间:2019-03-04 11:42:52

标签: java for-loop numbers drawing

我刚开始使用Java,我的老师要求我绘制以下形状的数字:

123456654321
 2345665432
  34566543
   456654
    5665
     66
    5665
   456654
  34566543
 2345665432 
123456654321

image

到目前为止,我可以使用以下代码绘制第一行和中间的一部分:

 int sz = 6;

    for (int i =1;i<=sz;i++)
        System.out.print(i);
    for(int j =sz;j>1;j--)
        System.out.print(j);

    for(int i =1; i<=sz;i++){
        System.out.println(i);
        for(int j=0;j<=i;j++){
            System.out.print(" ");
        }
    }

我在中体的其余部分都遇到了麻烦。 有人可以使用嵌套的for循环来帮助我画出那个吗?

2 个答案:

答案 0 :(得分:0)

您必须逐行走,因为println()之后,您将无法返回那里。

对于图案的上半部分,您可以使用它。

int sz = 6;

   for(int d = 1;d<=sz;d++){

    for (int i = d;i <= sz;i++) //for increasing numbers
        System.out.print(i);
    for(int j=sz;j>=d;j--)  //for decreasing numbers
        System.out.print(j);

    System.out.println(); //for newline

    for(int m=0;m<d;m++) // for spaces
        System.out.print(" ");
   }

答案 1 :(得分:0)

首先构建一个数组,然后遍历直线并构建它们:

int currentItem = 1;
int items[] = new int[12];
for (int index = 0; index < items.length; index++) {
    items[index] = (index < 6) ? currentItem++ : currentItem--;
}

for (int index2 = 0; index2 < 12; index2++) {
    String line = "";
    int limit = (index2 < 6) ? index2 : (12 - index2);
    for (int index3 = 0; index3 < items.length; index3++) {
        line += ((index3 >= limit) && (index3 < items.length - limit)) ? " " : items[index3];
    }
    System.out.println(line);
}