2017-02-11 43 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