Printer Friendly Version

BellaOnline's JavaScript / Java Editor

Fun With Java - Draw A Diamond

I recently found an interesting request from a Java student on one of the forums I read. His class had been asked to use a for loop to draw a diamond out of asterisks (*). He had a correct and functioning solution, but had been marked down because it was overly complicated and featured several loops. The student asked for suggestions on easier ways to achieve the same result. I thought this was an interesting problem and decided to try my hand at it. My program is below (or you can download a copy here.) This clearly isn't production code – for one thing, while I love the simplicity of the ?: operator, I try not to use it in production code because many programmers find that it makes it harder to read and understand. Not to mention, this code will break if max_width is changed to a number larger than 46. But it is an example of a fairly compact and logical method to achieve the desired result. Can you do better? Report back in our forum.

 * diamonds.java
 * Created on June 4, 2007, 11:39 PM

 * @author Julie Baumler
public class diamonds {

/** Creates a new instance of diamonds */
public diamonds() {

* @param args the command line arguments
public static void main(String[] args) {
int max_width=9; // # of chars wide to make diamond
int width=max_width % 2 == 0? max_width/2: max_width/2 +1;
String stars="**********************************************";
String spaces=" ";
for ( int i=1; i<(width*2); i++ ) {
System.out.print( spaces.substring(0, (i < width ? width -i : i%width)));
System.out.println(stars.substring(0,2*(i<=width? i : width-(i%width))-1 ));



The original request:
Pinimo. "Help me with java (sic)." Online posting. Week of 13 May 2007. Java Discussion (Forum). 4 June 2007 <http://www.mylot.com/w/discussions/1098760.aspx>.

This site needs an editor - click to learn more!

JavaScript / Java Site @ BellaOnline
View This Article in Regular Layout

Content copyright © 2013 by Julie L Baumler. All rights reserved.
This content was written by Julie L Baumler. If you wish to use this content in any manner, you need written permission. Contact Editor Wanted for details.

| About BellaOnline | Privacy Policy | Advertising | Become an Editor |
Website copyright © 2016 Minerva WebWorks LLC. All rights reserved.

BellaOnline Editor