The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
December 2000

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Pay me for java diamonds...

Posted by Kishori Sharan on December 08, 2000 at 10:11 AM

Compile and run Test.java and you will get three kinds of diamonds. Don't forget to pay me for these java diamonds!!!

////////////////Test.java ////////////
public class Test {
public static final void main(String [] args) {
int size = 3 ;

if ( args.length > 0 ) {
// Check if user passed any number
try {
size = Integer.parseInt ( args[0] ) ;
}
catch ( NumberFormatException e ) {
size = 4 ;
}
}

createFilledDiamond ( size ) ;
System.out.println ( ) ;

createLightDiamond ( size ) ;
System.out.println ( ) ;

createEmptyDiamond ( size ) ;
2System.out.println ( ) ;
}

public static void createFilledDiamond ( int size ) {
int i = 0 ;
int j = 0 ;
// Create upper half
for ( i = size, j = 1 ; i > 0 ; i--, j += 2 ) {
printChar ( " ", i ) ;
printChar ( "*", j ) ;
System.out.println ( ) ;
}

// Create lower half
for ( i = 0 ; j >= 1 ; i++, j -= 2 ) {
printChar ( " ", i ) ;
printChar ( "*", j ) ;
System.out.println ( ) ;
}
}


public static void createLightDiamond ( int size ) {
int i = 0 ;
int j = 0 ;
// Create upper half
for ( i = size, j = 1 ; i > 0 ; i--, j += 2 ) {
printChar ( " ", i ) ;
printOddChar ( "*", j ) ;
System.out.println ( ) ;
}

// Create lower half
for ( i = 0 ; j >= 1 ; i++, j -= 2 ) {
printChar ( " ", i ) ;
printOddChar ( "*", j ) ;
System.out.println ( ) ;
}
}

public static void createEmptyDiamond ( int size ) {
int i = 0 ;
int j = 0 ;
// Create upper half
for ( i = size, j = 1 ; i > 0 ; i--, j += 2 ) {
printChar ( " ", i ) ;
printExtremeChar ( "*", j ) ;
System.out.println ( ) ;
}

// Create lower half
for ( i = 0 ; j >= 1 ; i++, j -= 2 ) {
printChar ( " ", i ) ;
printExtremeChar ( "*", j ) ;
System.out.println ( ) ;
}
}


private static void printChar ( String str, int total ) {
for ( int i = 0 ; i < total ; i++ ) {
System.out.print ( str ) ;
}
}

private static void printOddChar ( String str, int total ) {
for ( int i = 1 ; i <= total ; i++ ) {
if ( i % 2 == 1 ) {
System.out.print ( str ) ;
}
else {
System.out.print ( " " ) ;
}
}
}

private static void printExtremeChar ( String str, int total ) {
for ( int i = 1 ; i <= total ; i++ ) {
if ( i == 1 || i == total ) {
System.out.print ( str ) ;
}
else {
System.out.print ( " " ) ;
}
}
}

}





Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us