Java Program: Printing the Letter "D" with Asterisks

Mar 7th, 2009 by ddenz11

done with the shapes and on with the letters!

Yup, after we have printed three shapes using asterisks namely, an inverted trianlge, a solid square, and a hollow square, we move on to some letters!

Like the previous programs, I have used two classes: one for printing the letter "D" and another as a test driver with the main method. Also, I still used for loops to get the solution. They come in very handy when you repeat a series of steps in the program, and with this particular case, printing asterisks.

I haven't mentioned in the previous articles that I have made but it really helps if you follow the program line by line, tracing the for loop if you will to understand it.

But if you have any trouble, just leave me a message or a comment below! :)

I also have learned documentation in Java! See the ones in /** and */? They’re really just special comments to put in your program describing every step. J You can ignore them, and even delete them if you want. It won’t change anything.

Here it goes:

/**

* the class uses a for loop to print asterisks (*) in the form of a letter 'D'

*

* @author Denzyll Jade C. Arcaya

* @version 03.03.2009

*/

public class LetterD

{

   

    private int width;

    private int height;

   

    /**

    * Constructor for objects of class LetterD

    */

   

    public LetterD(int init_Width, int init_Height)

    {

        width = init_Width;

        height = init_Height;

    }

    /**

    * toString - forms the letter 'D' using asterisks(*)

    *

    *

    * @return r    contains the letter 'D'

    */

   

    public String toString()

    {

        String r = "";

        for (int i=1; i<=height; i++)

        {

            if(i==1 || i==height){

                for(int j=1; j<=(width-1); j++)

                {

                    r = r + "*";

                }

                r = r + "\n";

            } else {

                r = r + "*";

                for (int j=1; j <=(width-2); j++)

                {

                    r = r + " ";

                }

                r = r + "*\n";

            }

        }

        return r;

    }

}

And this is the code for the driver. It prints out a letter “D” with a height and width equal to 7. (NOTE: it’s a different class!)

public class TesterDUH

{

  public static void main( String args[] )

  {

      LetterD d1 = new LetterD( 7,7);       System.out.println( d1.toString() );

  }

}

ddenz11

Written by ddenz11

Rate this Article:

Rating: 5.0/5 (1 votes cast)

Add new comment

* You must be logged in order to leave comments, please Sign in or join us.

Comments

No comments yet, be the first to comment on this article.