为什么我无法访问 Java 中 Point2D 的数据字段?
Why can't I access the data field of Point2D in Java?
我想使用 Point2D 创建一个包含 100 个随机点的数组。但是为什么Point2D的数据域是public,我却访问不到它的数据域呢?它说“x 无法解析或不是一个字段。”
public static void main(String[] args) {
Point2D[] points = new Point2D.Double[100];
for (int i = 0; i < points.length; i++) {
points[i] = new Point2D.Double();
points[i].x = Math.random() * 100;
points[i].y = Math.random() * 100;
}
}
您可能想要使用 setLocation。 error-message 只是说编译器不知道 .x 在 Point2D 类型的对象上应该意味着什么。
在您的代码中,points
的类型为 Point2D[]
,因此 points[i]
的类型为 Point2D
。 Point2D
没有名为 x
或 y
的成员。 points[i]
的 class 在运行时恰好是 Point2D.Double
,它确实有这样的成员,这一事实与编译器的分析无关。
您可以改为将 points
声明为
Point2D.Double[] points = new Point2D.Double[100];
,或者您可以使用 Point2D.setLocation()
而不是分配给成员变量,正如您的其他答案已经建议的那样。
我想使用 Point2D 创建一个包含 100 个随机点的数组。但是为什么Point2D的数据域是public,我却访问不到它的数据域呢?它说“x 无法解析或不是一个字段。”
public static void main(String[] args) {
Point2D[] points = new Point2D.Double[100];
for (int i = 0; i < points.length; i++) {
points[i] = new Point2D.Double();
points[i].x = Math.random() * 100;
points[i].y = Math.random() * 100;
}
}
您可能想要使用 setLocation。 error-message 只是说编译器不知道 .x 在 Point2D 类型的对象上应该意味着什么。
在您的代码中,points
的类型为 Point2D[]
,因此 points[i]
的类型为 Point2D
。 Point2D
没有名为 x
或 y
的成员。 points[i]
的 class 在运行时恰好是 Point2D.Double
,它确实有这样的成员,这一事实与编译器的分析无关。
您可以改为将 points
声明为
Point2D.Double[] points = new Point2D.Double[100];
,或者您可以使用 Point2D.setLocation()
而不是分配给成员变量,正如您的其他答案已经建议的那样。