列表空指针



我们开始在类中处理列表,并且有这项任务是在不创建新列表的情况下将数字与列表分开。所以我在列表中使用了 sepNum 标签和第一个。但是它返回 nullPointer ,我不明白为什么。空指针出现在单独的数字方法中的第二行。元素首先存在,并且为 !null。

public void separateNumbers() {
    sepNum = first;
    while (sepNum.info < 0 || sepNum.info > 9)
        sepNum = sepNum.point;
    Element previous = sepNum;
    Element current = sepNum.point;
    while (current != null) {
        if (current.info < 0 || current.info > 9){
            previous.point = current.point;
            current = current.point;
        } else {
            previous = current.point;
            current = current.point;
        }
    }
}

下面是元素类:

     class Element {
        char info;
        Element point;
        public Element (char ch) {
            this.info=ch;
            this.point=null;
        }
        public String toString() {
            return info+(point == null ? " " + point : "");
        }
    }

几个小时以来,我一直在试图弄清楚这一点。你们能帮忙吗?

您的问题在 while 循环中第二次出现。我已经用大括号中的值替换了变量。

public void separateNumbers()
{
    sepNum = {info: 'a', point: null};
    while ({'a'} < 0 || {'a'} > 9)  //sepNum.info
        sepNum = {null};            //sepNum.point

然后,再次返回到 while 循环以测试条件:

while ({null}.info < 0 || {null}.info > 9)    //sepNum.info

由于您正在引用 null,因此会出现 null 指针异常。

最新更新