在 Java 中绘制 "Square"
Drawing a "Square" in Java
我正在尝试使用星号在 Java 中绘制 "square"。我有一个带有输入参数的正方形 class,我正在尝试获取输出“”行的方法,以便连续有尽可能多的“”许多行作为存储在 class 实例变量 sideLength 中的值。所以如果代码做了一个 Square(3) 那么我想输出
通过名为 drawSquare 的方法。
到目前为止我有:
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);
}
}
最好的办法是使用 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.
}
因为这真的很简单,所以我不会给出解决方案,只会给出一些提示。
如果您查看自己制作的正方形,您会发现它的边长为 3,由 3 行每行 3 个星号组成。
要创建一个这样的行,您需要使用从 1 到 3 的 for()
循环并每次打印 "*"
。
因为您需要 3 行这样的行,所以您会将第一个循环包含在另一个循环中,该循环也是从 1 到 3。
作为最后的提示:System.out.print("*")
打印一个星号并且不另起一行。 System.out.println()
另起一行。
嵌套 for 循环是一种简单的方法:
for(int i = 0; i< y; i++){
for(int j = 0; j < x; j++){
System.out.print("*");
}
System.out.println();
}
我正在尝试使用星号在 Java 中绘制 "square"。我有一个带有输入参数的正方形 class,我正在尝试获取输出“”行的方法,以便连续有尽可能多的“”许多行作为存储在 class 实例变量 sideLength 中的值。所以如果代码做了一个 Square(3) 那么我想输出
通过名为 drawSquare 的方法。
到目前为止我有:
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);
}
}
最好的办法是使用 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.
}
因为这真的很简单,所以我不会给出解决方案,只会给出一些提示。
如果您查看自己制作的正方形,您会发现它的边长为 3,由 3 行每行 3 个星号组成。
要创建一个这样的行,您需要使用从 1 到 3 的 for()
循环并每次打印 "*"
。
因为您需要 3 行这样的行,所以您会将第一个循环包含在另一个循环中,该循环也是从 1 到 3。
作为最后的提示:System.out.print("*")
打印一个星号并且不另起一行。 System.out.println()
另起一行。
嵌套 for 循环是一种简单的方法:
for(int i = 0; i< y; i++){
for(int j = 0; j < x; j++){
System.out.print("*");
}
System.out.println();
}