空指针访问:变量nodeptr在此位置只能为空

Null pointer access: The variable nodeptr can only be null at this location

我有这段代码 当我 运行 它时我得到错误:

"Null pointer access: The variable nodeptr can only be null at this location"


static class point {
    double x;
    double y;
    double z;
    }

    static class problem {
            point[] nodeptr; 
    }
public static Tsp.point[] as_P_F()
    {

    Tsp.point[] nodeptr = null;


        for(int i=0;i<Input.General_Inputs.N;i++){
        nodeptr[i] = new Tsp.point();
        nodeptr[i].x = p[i];
        nodeptr[i].y = C[i];
        nodeptr[i].z = L[i];
        }

    return (nodeptr);
    }

我认为错误是因为我将 Tsp.point[] nodeptr 定义为 null 所以我做了以下代码:

public static Tsp.point[] as_P_F()
   {

    Tsp.point[] nodeptr = new Tsp.point[Input.General_Inputs.N];


        for(int i=0;i<Input.General_Inputs.N;i++){
        //nodeptr[i] = new Tsp.point();
        nodeptr[i].x = P[i];
        nodeptr[i].y = C[i];
        nodeptr[i].z = L[i];
        }

    return (nodeptr);
    }

但我不确定这是否正确这是我第一次使用这个概念我尝试在网上搜索但我没有找到任何有用的东西。有什么建议吗?

问题在这里:

public static Tsp.point[] assign_Pipe_Function()
    {

    Tsp.point[] nodeptr = null; // setting nodeptr to null. You have to initialize it with `new...`


        for(int i=0;i<Input.General_Inputs.Num_Of_Ppes;i++){
        nodeptr[i] = new Tsp.point();    // nodeptr is null so. nodeptr[i] will give NPE
        nodeptr[i].x = Pipe_Condition[i];
        nodeptr[i].y = Cof[i];
        nodeptr[i].z = Length[i];
        }

    return (nodeptr);
    }

您需要同时初始化数组和数组的单个 Tsp.point 个元素:

    Tsp.point[] nodeptr = new Tsp.point[Input.General_Inputs.N];

    for(int i=0;i<Input.General_Inputs.N_O_P;i++){
      nodeptr[i] = new Tsp.point();
      nodeptr[i].x = P[i];
      nodeptr[i].y = C[i];
      nodeptr[i].z = L[i];
    }