Java Square类
以下是我被要求做的: 1.创建一个名为Square的类,该类在构造函数中使用宽度参数。Square类应该有一个draw()方法,可以在屏幕上绘制正方形。创建一个名为TestSquare的类,该类将从用户获取宽度,创建一个Square对象,并对Square对象调用draw()方法
这就是我的问题,但我的问题是将draw()方法传递给test方法。我知道我需要将for循环从测试转移到类中,这样我就可以在test main方法中调用它
public class Square {
/** the width of square*/
int width;
/** construct the square*/
Square(){
}
/**construct a square */
Square(int newWidth){
width = newWidth;
}
/**show the square*/
void draw(){
for (int i=0; i<width; i++)
{
for (int j=0; j<width; j++)
{ System.out.print("* ");}
System.out.println();
}
}
}
import java.util.Scanner;
public class TestSquare {
/** Main method */
public static void main(String[] args) {
// Create a scanner input
Scanner input = new Scanner(System.in);
// prompt user to enter width
System.out.println("Creating a Square ...");
System.out.print("Please enter its width:");
int width = input.nextInt();
Square square = new Square(width);
System.out.println("Here is the Square:");
square.draw();
}
}
# 1 楼答案
这里有几个问题
将此方法重命名为“getArea”或仅返回宽度:
不要在for循环声明的末尾加分号。这使得for循环什么都不做。此外,外部for循环应该从0(而不是1)开始:
# 2 楼答案
将您的循环更改为:
如上所述,删除循环后的分号,因为这会使循环立即结束,而无需参数。我应该被设置为1,这样它就会以正确的次数重复
然后将getWidth()方法编辑为:
使用width*width将使方法返回n^2的宽度。应该是宽度而不是面积
编辑:我不确定这是否是你想要做的,但试着把它放在Square类中:
完全删除getWidth()方法。然后将getWidth()调用替换为: