简体   繁体   English

Java,使用点数组

[英]Java, using an array of points

I am writing a program in Java, in which I define a class我正在用 Java 编写程序,在其中定义了一个类

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;第一次命中该语句,其数组索引的值为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约翰·多纳

您必须在访问它之前初始化该值:

line[SampleSize - i + 1] = new Point();

That's because you have not created the points to put in the array那是因为您尚未创建要放入数组的点

for (int index = 0; index < line.length; index++)
{
    line[index] = new Point();
}
Point[]     line = new Point[6];

creates an empty array, capable of holding Points.创建一个空数组,能够保存点。 But does not hold any reference to a Point yet.但是还没有对 Point 的任何引用。 All are null.都是空的。

line[SampleSize - i + 1].x = i; 

tries to access x on a null .尝试在null上访问x

Just to add to Boris's answer, here is some code只是为了补充鲍里斯的答案,这里有一些代码

class Point {
    double x;
    double y;
}


Point[] line = new Point[6];
for(int i = 0; i < line.length; i++) {
    line[i] = new Point();
}

    // now you can set the values, since the point's aren't null
line[0].x = 10;
line[0].y = 10;

http://java.sun.com/docs/books/jls/third_edition/html/arrays.html 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.如果您在 10.2 节中注意到创建数组的行为只是创建了引用,而不是对象。 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:你需要做什么:

Point[] line = new Point[6];
for (int i = 0; i < line.length; i++)
{
    line[i] = new Point();
}

When you first create the array, it contains six null references.首次创建数组时,它包含六个null引用。

Before you can interact with objects in the array, you need to create the objects, like this:在与数组中的对象交互之前,您需要创建对象,如下所示:

line[someIndex] = new Point();

You probably want to initialize every point in the array using a for loop.您可能希望使用for循环初始化数组中的每个点。

java has a built in Point class java有一个内置的Point类

import java.awt.Point;

https://docs.oracle.com/javase/7/docs/api/java/awt/Point.html https://docs.oracle.com/javase/7/docs/api/java/awt/Point.html

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

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