Printing ASCII Diamond Drawing in Java

I am trying to print something like this:

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

So far, I have successfully printed the first part of the figure, but it was hard for me with the second part.

This is how I print the first part of the drawing:

 for (int fill = 0; fill <= ((2 * row - 1)); fill++) { if ((row % 2) == 0) { System.out.print("="); } else { System.out.print("-"); } } 

Second part i have

 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 result is as follows:

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

For complete code, please check: http://pastebin.com/YyCJ6Cq3

+6
source share
4 answers

As you can see, you are printing too many columns inside a diamond. Therefore, the correction should be simple: print one column each time, what you do, reducing the number of cycles during which your cycle runs by one. Generally speaking, you can simply add - 1 to the end of the conditional expression, as @samgak suggests, but this does not actually work. Try to understand why you are faced with this problem.

Your first loop is independent of n ; it uses only the current line index to determine the number of characters to print. A.

In the second loop, you must also include n to start large and decrease the fill value, but you are using it incorrectly. n and row are the same value (since row is defined in terms of n ), but you only multiply row by 2 . Instead, you must first perform the n-row operation, and then scale the result by 2 to print 2 characters on each line. You will have to play a little with it, since 2*(n-row) not quite right, but I hope this is enough to help you sort out your problem.

0
source

It looks like a school project, so I will give tips. The conditional expression looks like it has too much filling.

 fill <= (n - 2 * (row - 1)); 
0
source

Try: fill <= (n - (2 * (line -1) +1); Or: (n - 2 * (line -1));

0
source

Could you share all the code for this problem.

0
source

All Articles