Java Program: Printing a Solid Square using Asterisks

Feb 20th, 2009 by ddenz11

If this is a homework or a lab exercise for your computer science subject read on and get the solution!

The method for printing a solid square using "*" is I guess easier than printing an inverted triangle that I already showed you how to do. :)  Again here we have two classes one containing the method to print the shape and another with the main method. You can do this exercise with just one class but I’m used to making two classes having one test the other. So in my “Square” class I have a private variable “width” which is the desired width you want your square to be. I also added a constructor to set the value of “width” and finally the method “toString” to print the square. Again, I used “for” loops because it makes the solution a whole lot easier. J Here it goes:

// the class starts here!

public class Square {

    private int width;

//the constructor   

    public Square (int _width)

    {

        width = _width;

    }

//the method to print the square with a width of “width”

    public String toString(){

        String r = "";

        for(int i=1; i<=width ; i++){

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

                r = r+ "*";

            }

            r = r + "\n";

        }

        return r;

    }

}

So that's that.. :D We then make another class to test "Square". We will make another class "TestSquare" with the main method (using 10 as width, you can change this value if you want)

public class TestSquare {

    public static void main(String[] args) {

        Square a = new Square (10);

        System.out.print(a.toString());

    }

}

if you have any questions, please do leave a comment!

NOTE: This is a program that I made myself. I have tested it and came out with the desired output. I am also new in Java programming and I may not have applied the "elegant way" of writing Java programs. So please do understand. :D

ddenz11

Written by ddenz11

Rate this Article:

Rating: 4.6/5 (7 votes cast)

Add new comment

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

Comments

eric, over a year ago
Report comment

how about a square with a empty asterisk inside???

mpolenin, over a year ago
Report comment

You are doing OK. I am also taking into programming, and have been programming in Assembly, C, C++ (CLI and Win32), C#, JavaScript, and PHP.

Rexaniel Saburnido, over a year ago
Report comment

nice one i like programming too!! I am a 4th year BSECE student of MSU-IIT.