Christopher Miller Christopher Miller - 1 month ago 7
Java Question

Printing an ASCII Diamond: Bottom half broken?

I am attempting to print a diamond using a user inputted width of 7 that is supposed to look like this:

*
* *
* *
* *
* *
* *
*


BUT, unfortunately my diamond is messed up on the bottom and it looks like this:

*
* *
* *
* *
* *
*


Here's my code:

public static void main (String[] args)
{
int width = 0;
System.out.println("What is the width?");
Scanner keyboard = new Scanner (System.in);
width = keyboard.nextInt();

//Print top half of the diamond
for (int i = 0; i < width; i += 2) {
if (i == 0) {
for (int j = 0; j < (width / 2) + 1; j++)
System.out.print(' ');
System.out.print('*');
} else {
for (int j = 0; j < width - i; j += 2) {
System.out.print(' ');
}
System.out.print('*');
for (int j = 0; j < i - 1; j++) {
System.out.print(' ');
}
System.out.print('*');
}
System.out.print('\n');
}
//Print bottom half of the diamond
for (int i = 0; i < 3; i+=2) {
if (i == 2) {
for (int j = 0; j < (width / 2) + 1; j++)
System.out.print(' ');
System.out.print('*');
} else {
for (int j = 0; j <= i + 2; j += 2) {
System.out.print(' ');
} System.out.print ('*');
for (int j = 0; j < (width / 2) - i; j++) {
System.out.print(' ');
} System.out.print('*');
}
System.out.print('\n');
}
}


I am not totally sure how to fix the bottom part of it, that is what I have been trying to figure out! These nested for loops are tricky

Answer

For simple fix, change bottom loop variable i from 3 to 5, and line after that i from 2 to 4.

//Print bottom half of the diamond
for (int i = 0; i < 5; i+=2) {
    if (i == 4) {
        for (int j = 0; j < (width / 2) + 1; j++)
            System.out.print(' ');
        System.out.print('*');
    } else {
        for (int j = 0; j <= i + 2; j += 2) {
            System.out.print(' ');
        } System.out.print ('*');
        for (int j = 0; j < (width / 2) - i; j++) {
            System.out.print(' ');
        } System.out.print('*');
    }
    System.out.print('\n');
}