Search code examples
javashapesascii-art

Print an ASCII diamond of asterisks


My program that prints out a diamond like this:

...............*
..........*    *    *
.....*    *    *    *    *
*    *    *    *    *    *    *
.....*    *    *    *    *
..........*    *    *    
...............*

But it only works if the parameter or each side of the diamond is 4. For example if I input 6, the spacing on the bottom triangle is wrong and I been trying to figure it out.

The bottom triangle doesn't change when the parameter is changed, only the top one does. It only works for input 4.

public static void printMoreStars(int n) {
    int rowsPrime = 0;

    for (int i = n + 1; i > 0; i--) {
        for (int j = 0; j < (2 * i) - 1; j++) {
            System.out.print(" ");
        }
        for (int d = 0; d < (2 * rowsPrime) - 1; d++) {
            System.out.print("*" + " ");
        }
        System.out.println(); //new line character

        rowsPrime += 1;
        System.out.println(" ");
    }

    //bottom triangle
    for (int i = 1; i < n + 1; i++) {
        for (int j = 0; j < (2 * i) + 1; j++) {
            System.out.print(" ");
        }
        for (int d = 0; d < rowsPrime; d++) {
            System.out.print("*" + " ");
        }
        System.out.println(); //new line character

        rowsPrime -= 2;
        System.out.println(" ");
    }
}

Solution

  • You made two mistakes when using rowPrimes. See my annotations below:

    public class Stars {
        public static void main(String[] args) {
            printMoreStars(Integer.parseInt(args[0]));
        }
    
        public static void printMoreStars(int n) {
            int rowsPrime = 0;
    
            for (int i = n + 1; i > 0; i--) {
                for (int j = 0; j < (2 * i) - 1; j++) {
                    System.out.print(" ");
                }
                for (int d = 0; d < (2 * rowsPrime) - 1; d++) {
                    System.out.print("*" + " ");
                }
                System.out.println();   //new line character
    
                rowsPrime += 1;
                System.out.println(" ");
            }
    
            rowsPrime -= 2; // <- middle line is already printed, so skip that
    
            //bottom triangle
            for (int i = 1; i < n + 1; i++) {
                for (int j = 0; j < (2 * i) + 1; j++) {
                    System.out.print(" ");
                }
                for (int d = 0; d < (2 * rowsPrime) - 1; d++) { // <- changed condition to be the same as above
                    System.out.print("*" + " ");
                }
                System.out.println();   //new line character
    
                rowsPrime--; // <- you have to decrease rowPrime by one.
                System.out.println(" ");
            }
        }
    }