2015-02-10 55 views
0

我想弄清楚爲什麼我的鑽石並沒有完全形成在底部。當用戶輸入任何大於三的奇數時,鑽石在底部不能正確地形成(它僅在最大中線後面打印一行)。它看起來像這樣(我想在這個例子中五行):如何在爪哇形成鑽石

* 
    * * 
    * * * 
    * * 

我相信有什麼毛病了對於被認爲創造了鑽石底環。代碼爲:

//bottom of the diamond 
    for(j = (in + 1)/2; j < in; j++){ //similar to the first for statement instead when j equals the user's input plus one divided by two it will then go to the next for loop (the diamond starts to shrink) 
     for(i = 1; i < j; i++){ //when i equals one, and j is greater than one 
      System.out.print(" "); //prints space 
     } 
     for(l = 0; l < in - j; j++){ //similar to the for loop that prints the asterisk to the left this for loop goes through when l equals zero, and this time is less than the user's input minus j 
      System.out.print(" *"); //prints the bottom asterisks 
     } 
     System.out.println(""); //starts another blank new line 
    } //just like the top section it keeps looping until the requirements are no longer met 

我在做什麼錯了?

+5

'l = 0; l 2015-02-10 22:12:20

+0

謝謝你的糾正(驚訝我錯過了那個錯字)! – Fyree 2015-02-10 22:17:44

回答

0

儘管Lashane在他的評論中指出了直接的問題,但我注意到你的邏輯比需要的更復雜。

所以,在回答你的問題

我在做什麼錯?

允許我提供一個較少混淆的實現,該實現使用相同的循環體代碼鑽石的頂部和底部。

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

現在兩個for環路之間的唯一區別是,第一計數了從1in和第二計數回落從in - 11

+0

有趣的是,我將不得不嘗試一下,謝謝你的信息! – Fyree 2015-02-11 03:24:52