java - 为什么我的对象保持为空?

标签 java oop object nullpointerexception

出于某种原因,我似乎无法解决这个问题,导致出现 NullPointerException。我打印出poly.term. Degree 没有任何错误,然后将poly.next 设置为等于poly,然后当我尝试打印出看起来应该相同的poly.next.term. Degree 时得到一个nullPointerException。我知道这是不完整的代码,但我认为这是我的主要问题。

public Polynomial add(Polynomial p)
{   
    Polynomial newPoly = new Polynomial();

    newPoly.poly = new Node(0,0,null);

    Polynomial myCurr = this;

    Polynomial otherCurr = p;       

    while(myCurr.poly != null)
    {

        int myDeg = myCurr.poly.term.degree;
        int otherDeg = p.poly.term.degree;

        float myCo = myCurr.poly.term.coeff;
        float otherCo = otherCurr.poly.term.coeff;

        if(myDeg == otherDeg)
        {
            System.out.println("degrees "+myDeg + " and "+ otherDeg+ " are equal, creating new node...");

            Node n = new Node(myCo+otherCo,p.poly.term.degree, newPoly.poly.next);

            System.out.println(newPoly.poly.term.degree);

            newPoly.poly.next = newPoly.poly;
            newPoly.poly = n;

            System.out.println(newPoly.poly.next.term.degree); // Gives me a NullPointerException

        }

此外,这些类的构造函数和所有内容都在下面。

      package poly;

      import java.io.*;
      import java.util.StringTokenizer;

/**
 * This class implements a term of a polynomial.
 * 
 * @author runb-cs112
 *
 */
 class Term {
    /**
    * Coefficient of term.
    */
    public float coeff;

    /**
     * Degree of term.
     */
    public int degree;

    /**
     * Initializes an instance with given coefficient and degree.
     * 
     * @param coeff Coefficient
     * @param degree Degree
     */
    public Term(float coeff, int degree) {
        this.coeff = coeff;
        this.degree = degree;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#equals(java.lang.Object)
     */
    public boolean equals(Object other) {
        return other != null &&
        other instanceof Term &&
        coeff == ((Term)other).coeff &&
        degree == ((Term)other).degree;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    public String toString() {
        if (degree == 0) {
            return coeff + "";
        } else if (degree == 1) {
            return coeff + "x";
        } else {
            return coeff + "x^" + degree;
        }
    }
}

/**
 * This class implements a linked list node that contains a Term instance.
 * 
 * @author runb-cs112
 *
 */
class Node {

    /**
     * Term instance. 
     */
    Term term;

    /**
     * Next node in linked list. 
     */
    Node next;

    /**
     * Initializes this node with a term with given coefficient and degree,
     * pointing to the given next node.
     * 
     * @param coeff Coefficient of term
     * @param degree Degree of term
     * @param next Next node
     */
    public Node(float coeff, int degree, Node next) {
        term = new Term(coeff, degree);
        this.next = next;
    }

}

/**
 * This class implements a polynomial.
 * 
 * @author runb-cs112
 *
 */
public class Polynomial {

    /**
     * Pointer to the front of the linked list that stores the polynomial. 
     */ 
    Node poly;

    /** 
     * Initializes this polynomial to empty, i.e. there are no terms.
     *
     */
    public Polynomial() {
        poly = null;
    }

    /**
     * Reads a polynomial from an input stream (file or keyboard). The storage format
     * of the polynomial is:
     * <pre>
     *     <coeff> <degree>
     *     <coeff> <degree>
     *     ...
     *     <coeff> <degree>
     * </pre>
     * with the guarantee that degrees will be in descending order. For example:
     * <pre>
     *      4 5
     *     -2 3
     *      2 1
     *      3 0
     * </pre>
     * which represents the polynomial:
     * <pre>
     *      4*x^5 - 2*x^3 + 2*x + 3 
     * </pre>
     * 
     * @param br BufferedReader from which a polynomial is to be read
     * @throws IOException If there is any input error in reading the polynomial
     */
    public Polynomial(BufferedReader br) throws IOException {
        String line;
        StringTokenizer tokenizer;
        float coeff;
        int degree;

        poly = null;

        while ((line = br.readLine()) != null) {
            tokenizer = new StringTokenizer(line);
            coeff = Float.parseFloat(tokenizer.nextToken());
            degree = Integer.parseInt(tokenizer.nextToken());
            poly = new Node(coeff, degree, poly);
        }
    }

最佳答案

我认为问题出在这里:

        newPoly.poly.next = newPoly.poly;
        newPoly.poly = n;

一开始你会说,newPoly.poly.next = newPoly.poly;因此,您将当前元素分配给下一个元素,这是递归的。然后你说 newPoly.poly = n; 。因此,您将一个新元素分配给 newPoly。我认为垃圾收集器删除了 newPoly 元素,因为它被覆盖了,所以你失去了对 newPoly 元素的引用。这意味着当您稍后访问它时,您会收到空指针异常。你可以这样解决这个问题:

    newPoly.poly.next = n;
    //and dont forget to set the next pointer of the new elemnt to 0
    n.next = NULL;

只需将新元素分配给下一个元素即可。 编辑 @hendersawn

您可以对列表进行排序。见下文:

sort(Node head_p){ //do not change the head, or you will lose the beginning.
Node tmp_p; 
Node curr_p = head_p; 
while(curr_p != NULL){ 
if(curr_p.poly.term.degree < curr_p.next.poly.term.degree) //either degree is smaller or greater 
{//swap 
    tmp_p = curr_p; //save first element
    curr_p = curr_p.next; //set first element to second
    //now the 2 element is the actual third element so we need 
    //to put the first between the second and the third
    tmp_p.next = curr_p.next; //set next of first to third
    curr_p.next = tmp_p; //set second element to the first that we saved before
}
curr_p = curr_p.next; //move to next element...rinse repeat
}
}

关于java - 为什么我的对象保持为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25949978/

相关文章:

python - 是否可以声明一个类变量,该变量将产生其他两个类变量的总和

python - PyQt5 关闭事件方法

java - 我将如何编写自动检查以确保每个参数都有特定的注释?

java - Scala - 如何在运行时保证 val 不变性

java - 如何使用泛型(java)在编译时检测类差异

java - 锁定对象的方法 (Java)

c# - 是否可以返回多个不同类型的值?

javascript - 包含数组的对象数组可能吗?

java - Java原语可以被认为是轻型对象吗

Java 语法 : "synchronized (this)"