2014-02-17 88 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 
****** 
* * 
* * 
* * 
** 
*