Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

Printing Diamonds Java Output not exactly as required

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...