Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have developed a code to print a diamond in java. The code prints a diamond using * and "o" and the code is:

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--;
    }
}

The result I get from this is:

Diamond Height: 5

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

But Im trying to get the following results:

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.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
262 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can modify your inner loop logic when printing lower half of the diamond.

   //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("* ");
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...