JAVA双变量数学不符合,是二进制表示问题的BC?

问题描述:

基本上这是我不得不做的关于长方形的功课。当我需要做简单的数学计算顶点的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,这是正确的。

我一直在试图弄清楚为什么数学错了,但我仍然输了。任何帮助将非常感激!

这个赋值语句在任何构造函数之前完成。构造者首先来到无关紧要。所有的字段声明都是先处理的。

// 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'。 –

领域的其声明中的分配(如x1x2y1y2)被调用后super()并在构造函数中的任何其他语句之前完成。在你的情况下,中xywidthheight转让前发生如此x1x2y1y2将为0,如果你无论之前或之后的构造放置字段声明。

解决方案是在结尾处移动构造函数中的赋值。