基本上這是我不得不做的關於長方形的功課。當我需要做簡單的數學計算頂點的x和y值時,問題就出現了,例如(x-width/2),並且因爲我需要在多個方法中使用這些值,所以我在這個簡單的數學類(x1 =(x-width/2),x2,y1,y2等)中創建了新的變量),爲了可讀性。出於某種原因,在我的方法中,使用變量會產生錯誤的結果。當我回去並再次用數學替換它時,它就起作用了。JAVA雙變量數學不符合,是二進制表示問題的BC?
我的問題是爲什麼我所做的變量(在WEIDD VARIABLES下)不能在contains方法中工作?
這裏是我的代碼:
package com.example;
public class MyRectangle2D {
double x,y;
double width, height;
//a couple of getters and setters
//constructor
MyRectangle2D(){
x=0.0;
y=0.0;
width=1.0;
height=1.0;
}
MyRectangle2D(double X, double Y, double Width, double Height){
x=X;
y=Y;
width=Width;
height=Height;
}
// WEIRD VARIABLES
private double x1 = x-(width/2);
private double x2 = (x+(width/2));
private double y1 = (y-(height/2));
private double y2 = (y+(height/2));
//methods
boolean contains(double X, double Y){
/* initially wrote:
return (!(X<x1 || X>x2 || Y <y1 || Y>y2));
didnt work, bc for some reason x1,x2,y1,y2 were all 0.0
the below works well: */
return (!(X<(x-(width/2)) || X>(x+(width/2)) || Y <(y-(height/2)) || Y>(y+(height/2))));
}
public static void main(String[] args) {
MyRectangle2D b = new MyRectangle2D(1, 2, 3, 4);
System.out.println(b.x1); // 0.0 (should be -0.5)
System.out.println(b.x); // 1.0 (correct)
System.out.println(b. width); // 3.0 (correct)
System.out.println("(1.0,2.0) in b? (true?) " + b.contains(1.0,2.0)); //true (correct)
}
}
我完全罰款只是寫數學連連,但是在我的功課,他們希望我能創造一個方法來檢查,如果這個矩形包含另一個矩形,像
boolean contains(MyRectangle2D r){}
這意味着我需要編寫河(X-(寬度/ 2))= <(X-(寬度/ 2))等,以寫我的條件,這似乎繁瑣和雜亂。我認爲創建這些x1,x2,y1,y2變量是一種快捷方式是合乎邏輯的,因爲數學是相同的公式,它會更乾淨,我可以直接使用r.x1而不是r。(x-寬度/ 2))
tl; dr:當我println x1,它給我0.0,但是當我println x-(寬度/ 2),它給我-0.5,這是正確的。
我一直在試圖弄清楚爲什麼數學錯了,但我仍然輸了。任何幫助將非常感激!
的作品太好了!謝謝 – swonlek
你不能以靜態方法訪問'this'。 –