2017-02-11 44 views
-2

我已經開發了一個代碼來打印在java中的鑽石。該代碼打印使用*鑽石和「o」,代碼爲:打印鑽石Java輸出不完全按照要求

System.out.println("Diamond Height: " + DIAMOND_SIZE); 
    System.out.println("Output for: For Loop"); 

    int noOfRows = DIAMOND_SIZE; 

    //Getting midRow of the diamond 
    int midRow = (noOfRows)/2; 

    //Initializing row with 1 
    int row = 1; 

    //Printing upper half of the diamond 
    for (int i = midRow; i > 0; i--) 
    { 
     //Printing i spaces at the beginning of each row 
     for (int j = 1; j <= i; j++) { 
      System.out.print(" "); 
     } 

     //Printing j *'s at the end of each row 
     for (int j = 1; j <= row; j++) { 
      System.out.print("* "); 
     } 

     System.out.println(); 

     //Incrementing the row 
     row++; 
    } 

    //Printing lower half of the diamond 
    for (int i = 0; i <= midRow; i++) { 
     //Printing i spaces at the beginning of each row 
     for (int j = 1; j <= i; j++) { 
      System.out.print(" "); 
     } 

     //Printing j *'s at the end of each row 
     int mid = (row+1)/2; 
     for (int j = row; j > 0; j--) { 
     if(i==0 && j==mid) { 
      System.out.print("o "); 
     } 
     else { 
      System.out.print("* "); 
     } 
     } 

     System.out.println(); 

     //Decrementing the row 
     row--; 
    } 
} 

結果我從這個得到的是:

鑽石身高:5

* 
* * 
* o * 
* * 
    * 
Diamond Height: 3 
* 
* o 
* 

但我試着去獲得以下結果:

Diamond Height: 5 
     * 
    * * * 
    * * o * * 
    * * * 
     * 

Diamond Height: 3 
    * 
* o * 
    * 
What am I doing wrong? I have tried several things but nothing seems to help, Please help. 
+0

你試過嗎? – abl

+0

你知道中排,因此,中間的字符。測試你達到的時間並打印'o'而不是'*'。 – QBrute

回答

1

打印鑽石的下半部分時,可以修改內部循環邏輯。

//Printing j *'s at the end of each row 
int mid = (row+1)/2; 
    for (int j = row; j > 0; j--) 
    { 
     if(i==0 && j==mid) System.out.print("o "); 
      else System.out.print("* "); 
    } 
+0

我該怎麼去做while循環呢? – anon1234

+0

int j = row; while(j> 0){/ *在這裏插入你的代碼*/j--; } – algojava

+0

請看我發佈的答案,它似乎沒有工作。 – anon1234