简体   繁体   English

在Java中访问公共构造函数中的变量

[英]Accessing variables in public constructor in java

If you have 如果你有

class Triangle
{
  private double x1,x2,x3,y1,y2,y3;
  public Triangle(Point point1, Point point2, Point point3) 
  { 
    x1=point1.getX();
    y1=point1.getY();
    x2=point2.getX();
    y2=point2.getY();
    x3=point3.getX();
    y3=point3.getY();

    //Trying to get x and y values of point1-point3

  }

  double width=x1-x2;
  double length=y3-y2;

  public double area() 
  { 
    return (length * width)/2; 
  }
}

EDIT: I'm also only getting values for everything but length. 编辑:我也只获取长度以外的所有值。 length prints out 0 but y3 and y2 are still able to print values. length打印出0,但y3和y2仍然可以打印值。 I'm using a random number generator for doubles: 我正在为双打使用随机数生成器:

double randomValue = Math.random() * 100;

Could this be an issue with subtraction for doubles? 减去双打会不会成为问题?

I basically have points defined to take two variables x and y and I'm trying to calculate this area of a triangle. 我基本上已经将点定义为采用两个变量x和y,并且试图计算三角形的该面积。 When someone gives 3 points to make this triangle, I'm trying to get those values from the points and I do have getters for my points but I'm just ending up with nothing for length and width. 当有人给出3个点来制作这个三角形时,我试图从这些点中获取这些值,并且我的点确实有吸气剂,但最终却没有任何长度和宽度。

width and length should both be local variables inside of your area() method or inside of your constructor. widthlength都应该是area()方法内部或构造函数内部的局部变量。 It can be calculated in your constructor if this object is immutable, but I would say it is best to calculate them in the area() method if you expose getters/setters to the objects. 如果此对象是不可变的,则可以在构造函数中进行计算,但是我想说,如果将getter / setter暴露给对象,则最好在area()方法中对其进行计算。

public double area() 
{ 
    double width=x1-x2;
    double length=y3-y2;
    return (length * width)/2;
}

As you have it right now, they are package private members of your class, and are being set when you instantiate the class. 正如您现在所拥有的,它们是您的类的包私有成员 ,并且在您实例化该类时进行设置。

This code 此代码

double width=x1-x2;
double length=y3-y2;

Should be in your constructor. 应该在您的构造函数中。

As is it now, it is executed prior to the constructor, when x1,x2,y3,y2 are still 0. 现在,它在x1,x2,y3,y2仍为0时在构造函数之前执行。

  double width;
  double length;

  public Triangle(Point point1, Point point2, Point point3) 
  { 
    x1=point1.getX();
    y1=point1.getY();
    x2=point2.getX();
    y2=point2.getY();
    x3=point3.getX();
    y3=point3.getY();

    // init width and length after x1,x2,y3,y2 are intialized
    width=x1-x2;
    length=y3-y2;
  }

The alternative is to calculate width and length only when you need them : 另一种方法是仅在需要时才计算widthlength

  public double area() 
  { 
    double width=x1-x2;
    double length=y3-y2;
    return (length * width)/2; 
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM