Java程序遇到NullPointerException,该程序的哪一部分出错了?

时间:2018-10-01 03:17:27

标签: java nullpointerexception linked-list

这是从我的数据结构类中获得的,我们被要求添加两个由链表表示的数字。这些数字是后退的,这意味着最低有效数字在列表的前面。当总和小于10时,该程序运行良好。但是当我遇到类似9 + 2的东西时,eclipse会显示此“线程“主”中的异常” java.lang.NullPointerException”

这里是构造函数

    DigitNode(int digit, DigitNode next) {
            this.digit = digit;
            this.next = next;
    }

public static BigInteger add(BigInteger first, BigInteger second) {

        BigInteger newList = new BigInteger();
           DigitNode ptrF = first.front;
           DigitNode ptrS = second.front;
           DigitNode ptr = newList.front;

           if(first.negative == second.negative) {//both positive or negative
                  newList.negative = first.negative; 
                  int sum = 0;
                  int carry = 0;
                  int Fvalue= 0;
                  int Svalue = 0;

                  while(ptrF != null ||ptrS != null || carry != 0) {
                      sum = 0;
                      if (ptrF == null) {
                          Fvalue = 0;
                      } else {
                          Fvalue = ptrF.digit;
                      }

                      if (ptrS == null) {
                          Svalue = 0;
                      } else {
                          Svalue = ptrS.digit;
                      }



                      sum = Fvalue + Svalue + carry;
                      carry = 0;

                      if(sum > 9) {
                          sum = sum%10 + carry;
                          carry = 1;
                      }
                      if(newList.numDigits == 0) {newList.front = new DigitNode(sum,newList.front); newList.numDigits++;}
                      else {


                      ptr.next = new DigitNode(sum, null);
                      ptr = ptr.next;
                      newList.numDigits++;

                  }











                  }} 
           System.out.println("Parsing result:");
            System.out.println("Number of Digits: " + newList.numDigits);
            for (DigitNode ptrtest = newList.front; ptrtest != null; ptrtest = ptrtest.next) {
                System.out.print(ptrtest.digit + " - > ");
            }
            System.out.println();

          return newList;

    }

我在此行收到警告 “ ptr.next = new DigitNode(sum,null);”

0 个答案:

没有答案