我知道有一个类似的线程:
Calculating perimeter and area of a rectangle
但我仍然不知道该怎么办。
public class Rectangle {
double length, height, rectArea; // assigning variables for length, height and area of the rectangle
Point ul; // assigning variables for all corners
Point ur;
Point lr;
Point ll;
Rectangle(Point p_ul, Point p_ur, Point p_lr, Point p_ll) { //constructor assigning Point variables
ul = p_ul;
ur = p_ur;
lr = p_lr;
ll = p_ll;
}
Rectangle(int x_ul, int y_ul, int x_ur, int y_ur, int x_lr, int y_lr, int x_ll, int y_ll) { //constructor assigning coordinates for each corner Point variable
ul = new Point (x_ul, y_ul);
ur = new Point (x_ur, y_ur);
lr = new Point (x_lr, y_lr);
ll = new Point (x_ll, y_ll);
}
public double rectArea() {
double length = Math.sqrt( (ur.getX()-ul.getX()) * (ur.getX()-ul.getX()) ) + ( (ur.getY()-ul.getY()) * (ur.getY()-ul.getY()) ); //calculates length
double height = Math.sqrt( (ur.getX()-lr.getX()) * (ur.getX()-lr.getX()) ) + ( (ur.getY()-lr.getY()) * (ur.getY()-lr.getY()) ); //calculates height
return(length * height);
}
void displayInfo() { //Print statements
System.out.println("Rectangle Info: ");
System.out.println("Upper Left Point (x,y) : (" + ul.getX() + "," + ul.getY() + ")");
System.out.println("Upper Right Point (x,y) : (" + ur.getX() + "," + ur.getY() + ")");
System.out.println("Lower Left Point (x,y) : (" + ll.getX() + "," + ll.getY() + ")");
System.out.println("Lower Right Point (x,y) : (" + lr.getX() + "," + lr.getY() + ")");
System.out.println("Area: " + rectArea);
System.out.println("Length: " + length);
System.out.println("Height: " + height);
System.out.println("ur-lr(Y): " + (ur.getY()-lr.getY()));// this prints 4
System.out.println("ur-lr(X): " + (ur.getX()-lr.getX()));// this prints 0
}
}
我不确定为什么当我用实际的ul.get(X)等调用长度和高度时,会得到正确的长度和高度输出,但是当我打印“ length”和“ height”时,我得到的却是0,因此0区。
正如您最有可能告诉我的是n00b。谢谢你的帮助。
最佳答案
您有2个与实例变量同名的局部变量。这称为阴影变量。因此,当您通过方法调用它们时,您将获得正确的结果。但是您的实例变量尚未初始化。因此,它们的默认双精度值是0.0
像这样改变你的方法
public double rectArea() {
length = Math.sqrt((ur.getX()-ul.getX()) * (ur.getX()-ul.getX())) + ((ur.getY()-ul.getY()) * (ur.getY()-ul.getY())); //calculates length
height = Math.sqrt((ur.getX()-lr.getX()) * (ur.getX()-lr.getX())) + ((ur.getY()-lr.getY()) * (ur.getY()-lr.getY())); //calculates height
return(length * height);
}