2014-02-17 89 views
0

我有这样的代码,我试图打印以下形状了......倒车的Java For循环

**** 
* * 
** 
* 

目前代码:

System.out.print("\nEnter number of rows: "); 
    rows = kybd.nextInt(); 
    for (int i = 0; i < rows; i++) { 
     System.out.print("*"); 
    } 
    for (int i = 0; i < rows; i++) { 
     for (int j = 1; j <= i; j++) { 
      if (j == 1 || j == rows - 1 || j == i) { 
       System.out.print("*"); 
      } else { 
       System.out.print("0"); 
      } 
     } 
     System.out.println(); 
    } 

出于某种原因,它打印出像这个:

**** 
* 
** 
* * 

任何想法如何扭转第二个循环,所以它打印另一种方式?

+2

_For某种原因_...你要我们找到原因,因为你不知道如何调试? –

+6

'System.out.print(“0”)如何进入? – NPE

+1

你想'for(int i = rows - 1; i> 0; i - )'。你想在你进一步深入之前去阅读所有关于'for'循环的内容。 –

回答

3

我觉得你应该改变你的i循环

for (int i = rows - 1; i > 0 ; i--) 
0

请注意,您要在单独的循环中打印出星号的第一行,而不是在主格内。如果你想走这条路,你需要把第一个循环放在第二个循环的后面。

for (int i = 0; i < rows; i++) { 
    for (int j = 1; j <= i; j++) { 
     if ((j == 1) || (j == (rows - 1)) || (j == i)) { 
      System.out.print("*"); 
     } else { 
      System.out.print("0"); 
     } 
    } 
    System.out.println(); 
} 
for (int i = 0; i < rows; i++) { 
    System.out.print("*"); 
} 
+0

(虽然我认为“正确的解决方案”与分配可能是合并循环逻辑,但这确实解释了这种行为。) – user2864740

+0

这不符合OP的要求。 -1。 –

+0

@DavidWallace这个答案正确地解释了这个问题 - 它*无法通过修复第二个循环来解决(不包括终端魔术) - 并提出了一个解决方案。虽然我认为这不是“正确的课堂”解决方案,但现在已经回到了OP。 – user2864740

1

试试这个:

Scanner kybd = new Scanner(System.in); 
    System.out.print("\nEnter number of rows: "); 
    int rows = kybd.nextInt(); 

    if (rows > 1) { 
     for (int i = 0; i < rows; i++) 
      System.out.print("*"); 
     System.out.println(); 

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

输出示例:

Enter number of rows: 6 
****** 
* * 
* * 
* * 
** 
*