简体   繁体   中英

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);
    }
}

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.

Your best bet would be to use 2 nested for loops, to output a certain amount of asterisks in a line, then repeat that line the same amount of times.

for (int x = 0; x < sideLength; x++) {
    for (int y = 0; y < sideLength; y++) {
        System.out.print("*");
    }
    System.out.println(""); //Short for new line.
}

nested for loops are an easy way to do this:

for(int i = 0; i< y; i++){
    for(int j = 0; j < x; j++){
        System.out.print("*");
    }
    System.out.println();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM