ThoseKind ThoseKind - 1 year ago 95
Java Question

Drawing a "Square" in Java

I am trying to draw a "square" in Java using asterisks. I have a square class with an input parameter, I am trying to get the method to output lines of "" so that there are as many "" in a row and as many rows as the value stored in the class instance variable sideLength. So if the code has made a Square(3) then I want to output

Click for image

via a method called drawSquare.

So far I have:

class Square {

int sideLength;

Square( int size ) {
sideLength = size;

int getArea() {
return sideLength * sideLength;

int getPerimeter() {
return sideLength * 4;

void drawSquare() {

public static void main(String[] args) {
Square mySquare = new Square(4);
int area = mySquare.getArea();
int perimeter = mySquare.getPerimeter();
System.out.println("Area is " + area + " and perimeter is " + perimeter);
System.out.println("*" + )
Square mySquare2 = new Square(10);

Answer Source

As this is really easy, I'll give not the solution but just a few hints.

If you look at the square you made up, you'll see that, having a side-length of 3, it consists of 3 rows of 3 asterisks each.

To create one such row, you'd use a for() loop that goes from 1 to 3 and prints a "*" each time.

As you need 3 such rows, you'd enclose that first loop into another, that also goes from 1 to 3.

As final hint: System.out.print("*") prints an asterisk and does not start a new line. System.out.println() starts a new line.