I am working on a polynomial java assignment that consists of three different classes. The first class is a Term class which consists of two int types, coefficient and exponent. Second is the polynomial linked list class which has nodes that hold Term objects in them. And finally I have a driver class which contains the main method.
I have built the beginning of the classes and have started testing but I have run into an issue that continues to give me a NullPointerException. When I input my coefficient and exponent which will then create the Term object and place it inside a new Node, it throws this exception and I can't seem to find out why.
These are my classes:
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();
}
}
Any advice is truly appreciated. Some things are only there for testing, like the for loop in main, but I'm still getting the NullPointerException when running this code and entering in a coefficient and exponent.
-Bryant