2017-10-16 66 views
-12

我是Java初學者,我正在尋找一個製作星星鑽石的程序。 以下是我在網上找到:計數的用途是什麼 - 在程序中

public class JavaStarPattern { 

    public static void main(String[] args) { 
     int number = 5; 
     int count = number - 1; 
     for (int k = 1; k <= number; k++) { 
      for (int i = 1; i <= count; i++) 
       System.out.print(" "); 
      count--; 
      for (int i = 1; i <= 2 * k - 1; i++) 
       System.out.print("*"); 
      System.out.println(); 
     } 
     count = 1; 
     for (int k = 1; k <= number - 1; k++) { 
      for (int i = 1; i <= count; i++) 
       System.out.print(" "); 
      count++; 
      for (int i = 1; i <= 2 * (number - k) - 1; i++) 
       System.out.print("*"); 
      System.out.println(); 
     } 
    } 
} 

什麼用的count--count++? 爲什麼我們需要count--,在第二個for循環語句中,當我們在相同的語句中使用i++

+3

你可能想閱讀【JAVA教程](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html)。 –

+3

[堅果和螺栓:一元運算符](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html) –

+0

您可能還想調試代碼並逐步瞭解它它的確如此,一步一步來。 – Korashen

回答

0

在這裏,您可以看到完整的PROGRAMM更好的命名和文檔的幾行,如果你不理解你的代碼 - 文檔正確的方式....

public static void main(String[] args) { 
    int rows = 5; 
    int spaces = rows - 1; 
    int stars = 1; 

    // Print rows forwards 
    for (int k = 0; k < rows; k++) { 
     // print spaces at linebeginning 
     for (int i = 0; i < spaces; i++) 
      System.out.print(" "); 

     // print stars for this line 
     for (int i = 0; i < stars; i++) 
      System.out.print("*"); 

     // setting for next line 
     spaces--; // spaces -= 1 
     stars += 2; // add 2 more stars for each row 
     System.out.println(); 
    } 

    // turn around diamond 
    spaces = 1; // because longest line was printed before. 
    rows--; // need 1 row less 
    stars = ((rows - 1) * 2) - 1; // calculate stars MAX backwards 

    // print fows backwards 
    for (int k = 0; k < rows; k++) { 

     for (int i = 0; i < spaces; i++) 
      System.out.print(" "); 

     for (int i = 0; i < stars; i++) 
      System.out.print("*"); 

     // Settings 
     spaces++; 
     stars--; 
     System.out.println(); 
    } 
} 
相關問題