Java用嵌套循环打印数字三角形

时间:2013-03-17 17:37:32

标签: java for-loop nested-loops

我正在尝试使用Java中的嵌套循环打印以下内容:

1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1个

但它出现如下:

1 2 3 4 5 6
2 3 4 5 6
3 4 5 6
4 5 6
5 6
6

这是我的代码:

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

任何帮助将不胜感激。感谢

6 个答案:

答案 0 :(得分:1)

int n = 7;

for (int i = 1; i <= n; i++) {

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

}

答案 1 :(得分:0)

在内部第二个循环中设置此条件。

for (int j = 1; j <= 7 - i ; j++) 

修改:

完整的代码是

for (int i = 1; i <= 6; i++) {
    for (int j = 1; j < i; j++) 
    {
        System.out.print("  ");
    }
    for (int j = 1; j <= 7 - i ; j++) 
    {
        System.out.print(j + " ");
    }
    System.out.println();
}       

答案 2 :(得分:0)

您的计划应该是 -

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

由于

答案 3 :(得分:0)

for (int i = 2; i <= 7; i++) {
    for (int j = 2; j < i; j++) {
        System.out.print("  ");
    }
    for (int j = i; j <= 7; j++) {
        System.out.print(j-1 + " ");
    }
    System.out.println();
}

答案 4 :(得分:0)

这是相同的输出......请检查

public static void main(String[] args)
    { int c=0;

        for(int i=6;i>0;i--)
        {
            for(int k=0;k<c;k++)
              {
                  System.out.print("  ");
              }
              for (int j=1;j<=i;j++)
              {
               System.out.print(j +" ");
              }
              c++;
              System.out.println(" ");

        }  
    }

}

答案 5 :(得分:-1)

试试这个:

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

}