如何修复java中的DispatchUncaughtException

如何修复java中的DispatchUncaughtException,java,arrays,Java,Arrays,我试图用随机数生成一个数组,但它仍然显示dispatchUncaughtException。我对java完全陌生,有人能帮我解决这个问题吗 我写的代码如下: public class FindfreieGroundwaterlevel { public static void main(String[] args) { double[] groundwaterDistance = {-0.01,1.2,0,4.5,6.3,8.2,0,-1.7,2.1,0};

我试图用随机数生成一个数组,但它仍然显示
dispatchUncaughtException
。我对java完全陌生,有人能帮我解决这个问题吗

我写的代码如下:

public class FindfreieGroundwaterlevel {

    public static void main(String[] args) {
        double[] groundwaterDistance = {-0.01,1.2,0,4.5,6.3,8.2,0,-1.7,2.1,0};
        int [] index = new int [groundwaterDistance.length]; 
        int zero = 0;
        for (int n = 0; n < groundwaterDistance.length; n++ ) {   
            if (groundwaterDistance[n] == 0) {
                index[n] = n; 
            }else{
                index[n] = 0;
                zero++;
            }
        }             
        int[] newindex = new int[index.length - zero];
        int j = 0;
        for(int m : index) {
            if( m!= 0 ) {
               newindex[j] = m;
               j++;             
            }
        }   
        for (int i: newindex) {
            System.out.println(i);
        }

        Random generator = new Random(10);
        Coordinate[] position = new Coordinate[20];
        for (int i = 0; i <position.length; i++) {
            position[i].x = generator.nextDouble();
            System.out.println("x :" + position[i].x);
            position[i].y = generator.nextDouble();
            System.out.println("y :" + position[i].y);
            position[i].z = generator.nextDouble();
            System.out.println("z :" + position[i].z);            
        }
    }   
}
这是我得到的例外情况的图像:


调试器在出现异常时停止,因此您没有收到异常消息。如果继续执行,您将看到得到一个
NullPointerException
。这是因为您创建了一个空的
坐标[]
,然后尝试为
null
元素赋值

您需要在数组中创建一个
新坐标()。如果您创建一个接受x、y、z值的构造函数,那么它可能非常简单

for (int i = 0; i <position.length; i++) {
    position[i] = new Coordinate(generator.nextDouble(), generator.nextDouble(), generator.nextDouble());
}

for(int i=0;i您的调试器在异常处停止,因此您没有收到异常消息。如果继续执行,您会看到收到一个
NullPointerException
。这是因为您创建了一个空的
坐标[]
,然后尝试为
null
元素赋值

您需要在数组中创建一个
新坐标()

for (int i = 0; i <position.length; i++) {
    position[i] = new Coordinate(generator.nextDouble(), generator.nextDouble(), generator.nextDouble());
}
for(int i=0;i
for (int i = 0; i <position.length; i++) {
    position[i] = new Coordinate();
    position[i].x = generator.nextDouble();
    position[i].y = generator.nextDouble();
    position[i].z = generator.nextDouble();
}