Term对象的多项式链接列表返回NullPointerException

时间:2017-11-09 06:46:30

标签: java linked-list

我正在研究一个包含三个不同类的多项式java赋值。第一个类是Term类,它由两个int类型组成,系数和指数。第二个是多项式链表类,它具有在其中包含Term对象的节点。最后我有一个包含main方法的驱动程序类。

我已经构建了类的开头并且已经开始测试但是我遇到了一个问题,它继续给我一个NullPointerException。当我输入我的系数和指数然后创建Term对象并将其放在一个新的Node中时,它抛出了这个异常,我似乎无法找出原因。

这些是我的课程:

public class Term
{
    private int coefficient;
    private int exponent;

    public Term(int coefficient, int exponent)
    {
        this.coefficient = coefficient;
        this.exponent = exponent;
    }

    public int getCoefficient()
    {
        return coefficient;
    }

    public int getExponent()
    {
        return exponent;
    }
}

public class Polynomial
{
    private Node head;

    public Polynomial()
    {
        head = null;
    }

    public void readInPolynomial(int coef, int exp)
    {
        Term term = new Term(coef, exp);
        Node temp = new Node(term);
        if(head == null)
        {
            head = temp;
        }
        else
        {
            Node current = head;
            while(current.next != null)
            {
                current = current.next;
            }
            current.next = temp;
        }
    }

    public void printPolynomial()
    {
        if(head == null)
        {
            System.out.println("The polynomial is empty.");
        }
        else
        {
            Node current = head;
            while(current.next != null)
            {
                System.out.print(current.polyTerm.getCoefficient() + 
                                 "x^" + current.polyTerm.getExponent() 
                                 + " + ");

                current = current.next;
            }
            System.out.print(current.polyTerm.getCoefficient() + "x^" + 
                             current.polyTerm.getExponent());
        }
    }

    private class Node
    {
        private Term polyTerm;
        private Node next;

        public Node(Term polyTerm)
        {
            this.polyTerm = polyTerm;
            next = null;
        }
    }
}

public class PolynomialDriver
{
    private static Polynomial poly;

    public static void main(String[] args)
    {
        for(int i = 0; i < 2; i++)
        {
            Scanner keyboard = new Scanner(System.in);
            System.out.print("Enter the coefficient of your term: ");
            int coefIn = keyboard.nextInt();
            keyboard.nextLine();

            System.out.print("Enter the exponent of your term: ");
            int expIn = keyboard.nextInt();
            keyboard.nextLine();

            poly.readInPolynomial(coefIn, expIn);
        }
        poly.printPolynomial();
    }
}

真的很感激任何建议。有些东西只是用于测试,比如main中的for循环,但是在运行这段代码并输入系数和指数时,我仍然得到NullPointerException。

-Bryant

0 个答案:

没有答案