本文介绍了实现扩展 Rectangle 类的子类 Square的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//实现一个继承了Rectangle类的子类Square.在构造函数中,接受中心的 x 和 y 位置以及正方形的边长.打电话给Rectangle 类的 setLocation 和 setSize 方法.在Rectangle 类的文档.还提供一个方法 getArea 计算并返回正方形的面积.编写一个请求中心的示例程序和边长,然后打印出正方形(使用您从矩形继承)和正方形的面积.

//Implement a subclass Square that extends the Rectangle class. In the constructor,accept the x- and y-positions of the center and the side length of the square. Call thesetLocation and setSize methods of the Rectangle class. Look up these methods in thedocumentation for the Rectangle class. Also supply a method getArea that computesand returns the area of the square. Write a sample program that asks for the centerand side length, then prints out the square (using the toString method that youinherit from Rectangle) and the area of the square.

//好的...所以这是最后一分钟,但我不明白我的代码有什么问题它给了我一个错误,即 square 无法解析为一种类型...所以这是我的类:

//Ok... So this is last minute, but I don't understand what is wrong with my code it is giving me the error that square cannot be resolved to a type... So here is my Class:

    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
           + "]";
}
}

//And this is my tester class...

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);

  Square sq = new Square(x, y, length);
  System.out.println(sq.toString());

  }
}

//谁能帮助我的作业在午夜到期..它说编译时不能将square解析为测试类上的类型....

//Can anyone please help my assignment is due at midnight.. It says square cannot be resolved to a type on the tester class when compliling....

推荐答案

Square 不是您班级的名称.类的名称是Squares22".这就是无法识别正方形"的原因.将测试中的 Square 更改为 Squares22,反之亦然.这应该可以解决您的问题.

Square isn't the name of your class. The name of the class is 'Squares22'. This is why 'Square' cannot be recognized.Change Square in the test to Squares22 or vice versa. This should solve your issues.

这篇关于实现扩展 Rectangle 类的子类 Square的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 20:23