實現擴展Rectangle類的子類Square。在構造函數中,接受中心的x和y位置以及正方形的邊長。調用Rectangle類的setLocation和setSize方法。在Rectangle類的文檔中查找這些方法。另外提供一個方法getArea來計算和返回正方形的面積。大Java幫助?正方形和矩形
寫一個示例程序,詢問中心和邊長,然後打印出正方形(使用從矩形繼承的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());
}
}
這個問題被問了,我試過了答案,但我仍然得到一個錯誤?
的,什麼是錯誤? – TNT
你認爲這是做什麼? 'Squares22 sq = new Squares22();' –