Implement a subclass Square that extends the Rectangle class

放肆的年华 提交于 2019-12-13 09:01:15

问题


//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 the setLocation and setSize methods of the Rectangle class. Look up these methods in the documentation for the Rectangle class. Also supply a method getArea that computes and returns the area of the square. Write a sample program that asks for the center and side length, then prints out the square (using the toString method that you inherit from Rectangle) and the area of the 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()); 

  }
}

//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....


回答1:


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.



来源:https://stackoverflow.com/questions/16114743/implement-a-subclass-square-that-extends-the-rectangle-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!