2015-10-17 40 views
0

我需要編寫一個程序來讀取兩個點的X和Y座標,然後輸出矩形的面積和周長,其中兩個點都是對角。然而我得到這個錯誤信息MissingPropertyException錯誤(groovy)

groovy.lang.MissingPropertyException:No這樣的屬性:x對於類: 矩形。

有沒有人請幫忙解釋一下這裏出了什麼問題?

// First point 
Point point1 = new Point() 
print "enter first x co-ordinate: " 
point1.x = Double.parseDouble(System.console().readLine()) 
print "enter first y co-ordinate: " 
point1.y = Double.parseDouble(System.console().readLine()) 

// Second point 
Point point2 = new Point() 
print "enter second x co-ordinate: " 
point2.x = Double.parseDouble(System.console().readLine()) 
print "enter second y co-ordinate: " 
point2.y = Double.parseDouble(System.console().readLine()) 

// Create Rectangle 
Rectangle myRectangle = new Rectangle() 
myRectangle.upLeft = point1 
myRectangle.downRight = point2 

// Calculate Perimeter 
double width = myRectangle.downRight.x - myRectangle.upLeft.x 
double height = myRectangle.upLeft.y - myRectangle.downRight.y 
double perimeter = 2 * (width + height) 

// Calculate Area 
double area = width x height 

println "Perimeter is " + perimeter 
println "Area is " + area 


class Point { 
    double x 
    double y 
} 

class Rectangle { 
    Point upLeft 
    Point downRight 
} 
+0

這是整個代碼? –

回答

1

你在下面一行用x代替*

double area = width x height 

應該是:

double area = width * height 

不管怎麼說腳本正常運行。

+0

對,但這不是什麼原因造成的原始錯誤,是嗎? (不知道Groovy這麼多,我會很驚訝) –

+0

它也會導致它。嘗試在groovy控制檯中運行OP腳本。這是腳本失敗的地方。 – Opal

+0

好吧,不會在這一個下注:) –

0

錯誤解釋本身:

沒有這樣的屬性:X類:矩形。

您正在使用Rectangle類型的變量並要求提供屬性x但它不存在。這是Point類有這個屬性。

+0

但是,由於矩形類的字段是點並且分配的點是point1和point2(它們具有屬性x),那麼myRectangle也具有此屬性? 修復操作員錯誤後,代碼運行正常。感謝您的建議,但。 –

+0

不,'rectangle.x'永遠不會存在,例如'rectangle.upLeft.x'或'rectangle.downRight.y'。 –

+0

好的謝謝你澄清。 –