2017-09-16 76 views
0

基本上這是我不得不做的關於長方形的功課。當我需要做簡單的數學計算頂點的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,這是正確的。

我一直在試圖弄清楚爲什麼數學錯了,但我仍然輸了。任何幫助將非常感激!

回答

0

這個賦值語句在任何構造函數之前完成。構造者首先來到無關緊要。所有的字段聲明都是先處理的。

// 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)); 

也許你的問題的解決方案是使構造器內部的分配,如:

//declare the filds outside any method 
private double x1; 
private double x2; 
private double y1; 
private double y2; 

MyRectangle2D(){ 
    //... Your normal code here 
    buildWeird(); 
} 
MyRectangle2D(double X, double Y, double Width, double Height){ 
    //... Your normal code here 
    buildWeird(); 
} 
private void buildWeird(){ 
    this.x1 = x-(width/2); 
    this.x2 = (x+(width/2)); 
    this.y1 = (y-(height/2)); 
    this.y2 = (y+(height/2)); 
} 
+0

的作品太好了!謝謝 – swonlek

+0

你不能以靜態方法訪問'this'。 –

0

領域的其聲明中的分配(如x1x2y1y2)被調用後super()並在構造函數中的任何其他語句之前完成。在你的情況下,中xywidthheight轉讓前發生如此x1x2y1y2將爲0,如果你無論之前或之後的構造放置字段聲明。

解決方案是在結尾處移動構造函數中的賦值。