-2

我正在尝试使用 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();
}

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

4

6 回答 6

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

}
于 2013-12-19T06:47:31.960 回答
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(" ");

        }  
    }

}
于 2014-11-24T10:11:45.023 回答
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();
}
于 2014-09-26T14:40:15.490 回答
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();
}       
于 2013-03-17T17:40:38.760 回答
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();
}

谢谢

于 2013-03-17T17:40:52.797 回答
-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();  

}

于 2013-03-17T17:40:54.207 回答