为什么我无法在Java中访问Point2D的数据字段?

huangapple go评论74阅读模式
英文:

Why can't I access the data field of Point2D in Java?

问题

我想使用Point2D创建一个包含100个随机点的数组。但为什么我无法访问其数据字段,而Point2D的数据字段是公共的?它显示“无法解析x,或者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;
    }
}
英文:

I want to create an array of 100 random points using Point2D. But why can't I access its data field while the data field of Point2D is public? It said "x cannot be resolved or not a field."

public static void main(String[] args) {
			
	Point2D[] points = new Point2D.Double[100];
	for (int i = 0; i &lt; points.length; i++) {
		points[i] = new Point2D.Double();
		points[i].x = Math.random() * 100;
		points[i].y = Math.random() * 100;
	}
}

答案1

得分: 0

你可能想使用setLocation方法。错误信息只是说编译器不知道在类型为Point2D的对象上,.x应该表示什么。

英文:

You might want to use setLocation. The error-message just says that the compiler doesn't know what .x is supposed to mean on an object of type Point2D.

答案2

得分: 0

在你的代码中,points 的类型是 Point2D[],因此 points[i] 的类型是 Point2DPoint2D 没有名为 xy 的成员。在运行时,points[i]恰好是 Point2D.Double,而这个类具有这样的成员,但这与编译器的分析无关。

你可以改为将 points 声明为

Point2D.Double[] points = new Point2D.Double[100];

或者你可以使用 Point2D.setLocation() 方法来代替直接赋值给成员变量,正如你的其他回答中已经建议的那样。

英文:

In your code, points has type Point2D[], therefore points[i] has type Point2D. Point2D does not have members named x or y. The fact that at runtime the class of points[i] happens to be Point2D.Double, which does have such members, is irrelevant to the compiler's analysis.

You could instead declare points as

    Point2D.Double[] points = new Point2D.Double[100];

, or you could use Point2D.setLocation() instead of assigning to member variables, as your other answer already suggests.

huangapple
  • 本文由 发表于 2020年10月14日 06:46:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/64344199.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定