由于java无法找到我放置的变量的问题,我一直遇到此任务的问题。作业是: 实现具有以下属性的Rectangle类。
在构造函数中指定Rectangle对象,矩形的左右边缘位于x和x + width处。顶部和底部边缘位于y和y +高度。
方法getPerimeter计算并返回Rectangle的周长。
方法getArea计算并返回Rectangle的区域。
方法绘制显示Rectangle对象的新实例。有关DrawingTool方法的详细信息,请参阅DrawingTool API。
使用默认构造函数和可以获取x和y坐标,矩形长度和宽度的构造函数来尝试矩形。以下是一些示例构造函数调用:
Rectangle rectA = new Rectangle();
Rectangle rectB = new Rectangle(0,-80,400,160);
Rectangle rectC = new Rectangle(100,-100,20,300);
这是我的作业驱动程序:
public class Driver_class
{
public static void main(String[] args) {
P4_Icel_Murad_Rectangle rectA = new P4_Icel_Murad_Rectangle();
P4_Icel_Murad_Rectangle rectB = new P4_Icel_Murad_Rectangle(0,-80,400,160);
P4_Icel_Murad_Rectangle rectC = new P4_Icel_Murad_Rectangle(100,-100,20,300);
}
}
和我的主要()
public class P4_Icel_Murad_Rectangle
{
/**
* Constructor for objects of class P4_Icel_Murad
*/
public P4_Icel_Murad_Rectangle(double x, double y, double width, double height)
{
// initialise instance variables
DrawingTool Pen;
SketchPad Paper;
//new sketchpad
Paper = new SketchPad(500,500);
Pen = new DrawingTool(Paper);
getPerimeter();
getArea();
draw();
}
//Constructor # 2
public P4_Icel_Murad_Rectangle()
{
double x = 0;
double y = 0;
double width = 0;
double height = 0;
DrawingTool Pen;
SketchPad Paper;
//new sketchpad
Paper = new SketchPad(500,500);
Pen = new DrawingTool(Paper);
getPerimeter();
getArea();
draw();
}
public double getPerimeter(){
double per = (width * 2) + height * 2;
return per;
}
public double getArea(){
double area = width * height;
return area;
}
public void draw(){
pen.down();
pen.turnRight(90);
pen.forward(x);
pen.turnLeft(90);
pen.forward(width);
pen.turnLeft(90);
pen.forward(height);
pen.turnLeft();
pen.forward(y);
}
}
Java说它无法找到变量宽度,尽管我已经列出了它。感谢您的帮助!
答案 0 :(得分:0)
您的变量仅在构造函数的范围内声明。在课堂上让他们private
。
答案 1 :(得分:0)
public static class P4_Icel_Murad_Rectangle {
SketchPad Paper = new SketchPad(500, 500);
DrawingTool pen = new DrawingTool(Paper);
double x = 0;
double y = 0;
double width = 0;
double height = 0;
/**
* Constructor for objects of class P4_Icel_Murad
*/
public P4_Icel_Murad_Rectangle(double x, double y, double width, double height) {
// initialise instance variables
getPerimeter();
getArea();
draw();
}
// Constructor # 2
public P4_Icel_Murad_Rectangle() {
getPerimeter();
getArea();
draw();
}
public double getPerimeter() {
double per = (width * 2) + height * 2;
return per;
}
public double getArea() {
double area = width * height;
return area;
}
public void draw() {
pen.down();
pen.turnRight(90);
pen.forward(x);
pen.turnLeft(90);
pen.forward(width);
pen.turnLeft(90);
pen.forward(height);
pen.turnLeft();
pen.forward(y);
}
}