实现扩展Rectangle类的子类Square。在构造函数中,接受中心的x和y位置以及正方形的边长。调用Rectangle类的setLocation和setSize方法。在Rectangle类的文档中查找这些方法。还提供了一个getArea方法,用于计算并返回方形区域。
编写一个示例程序,询问中心和边长,然后打印出正方形(使用从Rectangle继承的toString方法)和方形区域。
import java.awt.Rectangle;
public class Squares22 extends Rectangle
{
public Squares22(int x, int y, int length) {
setLocation(x - length / 2, y - length / 2);
setSize(length, length);
}
public int getArea() {
return (int) (getWidth() * getHeight());
}
public String toString() {
int x = (int) getX();
int y = (int) getY();
int w = (int) getWidth();
int h = (int) getHeight();
return "Square[x=" + x + ",y=" + y + ",width=" + w + ",height=" + h
+ "]";
}
}
import java.util.Scanner;
public class Squares22Tester
{
public static void main(String[] args)
{
Scanner newScanx = new Scanner(System.in);
Scanner newScany = new Scanner(System.in);
Scanner newScanl = new Scanner(System.in);
System.out.println("Enter x:");
String x2 = newScanx.nextLine();
System.out.println("Enter y:");
String y2 = newScany.nextLine();
System.out.println("Enter length:");
String l2 = newScanl.nextLine();
int x = Integer.parseInt(x2);
int y = Integer.parseInt(y2);
int length = Integer.parseInt(l2);
Squares22 sq = new Squares22();
System.out.println(sq.toString());
}
}
这个问题被问到了,我尝试了答案,但我仍然收到错误?
答案 0 :(得分:1)
new Squares22();
这不是该类定义的构造函数,并且您没有使用变量...
new Squares22(x,y,length);
可能会更好......