thuzle thuzle - 4 months ago 19
Java Question

Printing ASCII Diamond Figure in Java

I trying to print something like this:

+--------+
| /\ |
| /--\ |
| /====\ |
|<------>|
| \====/ |
| \--/ |
| \/ |
+--------+


So far I have sucessfully printed the first part of the figure but having a hard time with the second part.

This is how I am printing the first part of the figure:

for (int fill = 0; fill <= ((2 * row - 1)); fill++) {

if ((row % 2) == 0) {
System.out.print("=");
} else {
System.out.print("-");
}
}


The second part I have is

for (int fill = 0; fill <= (n - 2 * (row - 1)); fill++) { //This is where I need help
if ((row % 2) == 0) {
System.out.print("=");
} else {
System.out.print("-");
}
}


My outcome looks like this:

+--------+
| /\ |
| /--\ |
| /====\ |
|<------>|
| \=====/ |
| \---/ |
| \=/ |
+--------+


For the full code please check: http://pastebin.com/YyCJ6Cq3

Answer

As you can see you're printing one too many columns inside the diamond. So the fix should be simple - print one less column each time, which you do by reducing the number of times the your loop runs by one. Generally speaking you could just add a - 1 to the end of the conditional like @samgak suggests, but this won't actually work here. Let's try to understand why you're running into this issue.

Your first loop doesn't depend on n; it only uses the current row index to determine how many characters to print.

In the second loop you correctly need to also include n in order to start large and decrease the value of fill, but you're misusing it. n and row are of the same magnitude (since row is defined in terms of n) yet you only multiply row by 2. Instead you should do the n-row operation first, then scale the result by 2 in order to print 2x characters in each row. You'll have to play with it a little further since 2*(n-row) isn't quite right, but hopefully that's enough to help you figure out your issue.

Comments