Java,使用点数组
我正在用Java编写一个程序,其中我定义了一个类
class Point
{
double x;
double y;
}
中,我定义了一个点数组,如下所示:
Point[] line = new Point[6];
然后在一个方法
line[SampleSize - i + 1].x = i;
, 数组索引为1; 但此时程序抛出空指针异常。
这似乎是索引对象字段的正确方法 对象数组。我做错了什么?
预先感谢您的任何建议。
约翰·多纳
I am writing a program in Java, in which I define a class
class Point
{
double x;
double y;
}
Then in a method, I define an array of points, as follows:
Point[] line = new Point[6];
In the same method, I have the line
line[SampleSize - i + 1].x = i;
The first time this statement is hit, the value of its array index is 1;
but the program throws a null pointer exception at this point.
This would seem like the correct way to index the field of an object within an
array of objects. What am I doing wrong?
Thanks in advance for any suggestions.
John Doner
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您必须在访问该值之前对其进行初始化:
You have to initialize the value before accessing it:
那是因为您还没有创建要放入数组中的点
That's because you have not created the points to put in the array
创建一个空数组,能够保存 Points。但还没有任何对 Point 的引用。全部为空。
尝试在
null
上访问x
。creates an empty array, capable of holding Points. But does not hold any reference to a Point yet. All are null.
tries to access
x
on anull
.只是为了添加鲍里斯的答案,这里有一些代码
Just to add to Boris's answer, here is some code
http://java.sun.com/docs/books/jls /third_edition/html/arrays.html
如果您注意到第 10.2 节中创建数组的行为只是创建引用,而不是对象。因此,空指针错误的原因是,所有引用都被赋予默认值,在本例中为空。
http://java.sun.com/docs/books/jls/third_edition/html/arrays.html
If you note in Section 10.2 the act of creating an array simply creates the references, but not the objects. Hence the reason for your null pointer error, all of the references are given the default value, which in this case is null.
尽管您已经分配了数组,但数组的内容为空。你需要做什么:
Although you have allocated the array, the contents of the array are null. What you need to do:
首次创建数组时,它包含六个
null
引用。在与数组中的对象交互之前,您需要创建对象,如下所示:
您可能希望使用
for
循环初始化数组中的每个点。When you first create the array, it contains six
null
references.Before you can interact with objects in the array, you need to create the objects, like this:
You probably want to initialize every point in the array using a
for
loop.java 有一个内置的 Point 类
https://docs .oracle.com/javase/7/docs/api/java/awt/Point.html
java has a built in Point class
https://docs.oracle.com/javase/7/docs/api/java/awt/Point.html