2016-08-01 40 views
0

我想打印一个由0开始并以9结尾的数字金字塔,当它等于9时,程序应该从0重新开始到9,等等......以0开头的数字金字塔结尾为9

这是我曾尝试:

public static void main(String[] args) { 

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

其印刷

 0 
    0 1 2 
    0 1 2 3 4 
    0 1 2 3 4 5 6 
    0 1 2 3 4 5 6 7 8 

但我需要这个..

  0 
     1 2 3 
     4 5 6 7 8 
    9 0 1 2 3 4 5... 
+1

而你得到的是什么? – Jens

+0

http://i.stack.imgur.com/wprNW.png我得到这个.. –

+0

提示:为什么你总是从0打印k? – venki421

回答

1

您打印k0开始为i每次迭代打印0 1 2 3..每次。相反,请创建一个初始化为0的局部变量并将其打印并每次增加一个。在你的情况下,你想从0开始计数,当counter值大于9时,你可以添加一个检查,包括if(counter > 9) counter = 0;。新增以下代码:

int counter = 0; 
for (int i = 0; i < 10; i += 2) { 
for (int j = 0; j < 20 - i; j++) { 
    System.out.print(" "); 
} 
for (int k = 0; k <= i; k++) { 
    System.out.print(" " + counter++); 
    if(counter > 9) counter = 0; 
} 

System.out.println(); 
} 

输出

   0 
      1 2 3 
     4 5 6 7 8 
     9 0 1 2 3 4 5 
    6 7 8 9 0 1 2 3 4 

DEMO

+0

为什么'j <20'?这只会缩小金字塔,可能不会被通缉。而不是如果增加计数器,你可以做'System.out.print(“”+(counter ++%10));'。 – Thomas

+0

好的工作(不)。现在他只能复制你的代码,错过了调试自己代码的学习经验。 –

+0

@Thomas是'j <20'是可选的我添加了额外的空间。我发布了首先出现在我脑海中的代码,但是感谢其他解决方案。 – silentprogrammer

0

您可以有一个变量并每次增加它。

public static void main(String[] args) { 
    int count=0; 
    for (int i = 0; i < 10; i += 2) { 
     for (int j = 0; j < 10 - i; j += 2) { 
      System.out.print(" "); 
     } 
     for (int k = 0; k <= i; k++) { 
      System.out.print(" " + count++); 
      if(count>9) 
       count=count%10; 
     } 

     System.out.println(); 
    } 
}