简体   繁体   English

用Java绘制“平方”

[英]Drawing a “Square” in Java

I am trying to draw a "square" in Java using asterisks. 我正在尝试使用星号在Java中绘制一个“正方形”。 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. 我有一个带有输入参数的方形类,我试图获取输出“ 行的方法,以使 ”和存储在类实例变量sideLength中的值一样多。 So if the code has made a Square(3) then I want to output 因此,如果代码已做成Square(3),那么我想输出

Click for image 点击图片

via a method called drawSquare. 通过名为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. 如果查看组成的正方形,则边长为3的正方形将包含3行,每行3个星号。

To create one such row, you'd use a for() loop that goes from 1 to 3 and prints a "*" each time. 要创建这样的一行,您可以使用for()循环,该循环从1到3,每次都打印一个"*"

As you need 3 such rows, you'd enclose that first loop into another, that also goes from 1 to 3. 当您需要3个这样的行时,可以将第一个循环封装到另一个循环中,该循环也从1到3。

As final hint: System.out.print("*") prints an asterisk and does not start a new line. 最后提示: System.out.print("*")打印一个星号,并且不开始新行。 System.out.println() starts a new line. System.out.println()开始新行。

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. 最好的选择是使用2个嵌套的for循环,在一行中输出一定数量的星号,然后将该行重复相同的次数。

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循环是执行此操作的简单方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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