Tuesday, April 17, 2012

Prinitng diamond in java

In this problem, your mission is to write a function
private void drawDiamondOutline(int size)
that draws the outline of a diamond whose sides are composed of the number of stars
indicated by size. For example, if your run method is
public void run() {
drawDiamondOutline(8);
}
your program should print asterisks and spaces in just the right places to produce the
following sample run:
*
* *
* *
* *
*
/**
* @author gagandsi
*
*/
public class DiamondOutline {

private void drawDiamondOutline(int size) {
// Upper triangle //
size -= 2;
for (int j = 0; j < size + 1; j++)
System.out.print(" ");
System.out.println("*");
for (int k = size; k > 0; k--) {

for (int j = 0; j < k; j++)
System.out.print(" ");

System.out.print("*");

for (int jj = size; jj > k - 1; jj--) {
System.out.print(" ");
}
for (int jj = size; jj > k; jj--) {
System.out.print(" ");
}
System.out.print("*");
System.out.println("");

}

// Lower triangle//

for (int i = 0; i < size + 1; i++) {
for (int x = 0; x < i; x++)
System.out.print(" ");

System.out.print("*");

for (int jj = 0; jj < size - i + 1; jj++) {
System.out.print(" ");
}
for (int jj = 0; jj < size - i; jj++) {
System.out.print(" ");
}
System.out.print("*");
System.out.println("");
}
for (int j = 0; j < size + 1; j++)
System.out.print(" ");
System.out.println("*");
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new DiamondOutline().drawDiamondOutline(5);

}

}


You might want to add a check for negative or zero as input.

No comments: