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

时间:2015-02-20 05:15:27

标签: java eclipse pointers null

我有这个代码当我运行它时我收到错误:

"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);
    }

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

2 个答案:

答案 0 :(得分:0)

问题在于:

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);
    }

答案 1 :(得分:0)

您需要初始化数组的数组和单个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];
    }