2017-02-11 2 views
-2

Ich habe einen Code zum Drucken eines Diamanten in Java entwickelt. Der Code druckt einen Diamanten mit * und "o" und der Code ist:Drucken von Diamanten Java Ausgabe nicht genau wie erforderlich

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

Das Ergebnis, das ich von diesem erhalten ist:

Diamant Höhe: 5

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

Aber Im versuchen, Erhalten Sie die folgenden Ergebnisse:

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

Haben Sie es versucht? – abl

+0

Sie kennen die mittlere Reihe und folglich die mittlere Figur. Testen Sie, wann Sie das erreicht haben, und drucken Sie "o" anstelle von "*". – QBrute

Antwort

1

Sie können Ihre innere Schleifenlogik ändern, wenn Sie die untere Hälfte des Diamanten drucken.

//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

Wie würde ich das mit While-Schleifen machen? – anon1234

+0

int j = Reihe; while (j> 0) {/ * gib hier deinen Code ein */j--; } – algojava

+0

Bitte schauen Sie auf die Antwort, die ich gepostet habe, es scheint nicht zu funktionieren. – anon1234