尝试将对象转换为字符串时获取NullPointerException

时间:2019-05-06 10:58:02

标签: java nullpointerexception tostring

对不起,如果代码有点混乱。我试图将一个对象(从我的节点类通过getData)转换为一个int。由于某种原因,它会在null检查之后继续在'addNode'下返回NullPointerException

任何帮助将非常感激,谢谢!

我尝试过在valueOftoString之间进行操作,但是两者都存在相同的问题。所以在这一点上,我挠头了,因为我对这种事情的了解还不是很深入,可能是什么原因引起的。

此外,我在导致错误的代码片段之前使用了getData,似乎可以很好地提取数据,这意味着getData不会出现让我更加沮丧的问题。

我的构造函数有:

protected node root = new node();
private node temp = new node();

和具体存在问题的addNode是:

protected void addNode(int desiredNode){
        addNode(desiredNode, root.getLinkRight());
    }
    private void addNode(int desiredNode, node temp){


        /**check to see if it already exists or if the root actual is null,
        this will run every time the function is recursively run.
        I could not think of a clever way to avoid this without a bit of extra
        overhead in the magnitude of creating specific methods to handle this.**/

        if(root.getLinkRight()==null){
            System.out.println("derp");
            node nodeNew = new node();
            nodeNew.setData(desiredNode);
            nodeNew.setParent(null);
            root.setLinkRight(nodeNew);
            System.out.println(root.getLinkRight().getData() + "teest");
        }

        System.out.println(temp.getData()+"test23");
        Object tempString = temp.getData();
        String tempComparator = String.valueOf(tempString);
        int comparator = Integer.parseInt(tempComparator);



        if(findNode(desiredNode)!=null){
            System.out.println("Error: Node already exists! Ignoring.");
            return;
        }

        int i = 0;
        if(comparator<desiredNode){
            if(temp.getLinkRight()==null){
                i = 1;
            }
            temp = temp.getLinkRight();
            addNode(desiredNode, temp);
        }
        else if(comparator>=desiredNode){
            if(temp.getLinkLeft()==null){
                i = -1;
            }
            temp = temp.getLinkLeft();
            addNode(desiredNode, temp);
        }

        node nodeNew = new node();
        nodeNew.setData(desiredNode);
        nodeNew.setParent(temp);
        if(i==1){
        }
    }

这是一个项目,我的add和remove方法都要求它们是递归的。

我想将其转换为一个int,以便在添加时可以进行比较以查找它应该在树上的哪个位置。

大多数无法解释的方法都是很容易解释的。如果您需要更多信息,请告诉我。

0 个答案:

没有答案