Search code examples
javasingly-linked-listpolynomials

Custom LinkedList implementation to store terms of a polynomial


For a homework assignment I'm working on you're required to create a custom LinkedList data structure to hold the terms of a polynomial. I'm having a problem at the moment with my constructor adding terms to the data structure because it needs to accept a string like "5.2 3 2.1 2" (which would be the equivalent of 5.2^3 + 2.1^2) and store it in the my custom LinkedList. Some of the requirements include that terms cannot have coefficients of zero, exponents must be integers, and coefficients can be either integers or doubles. When I trace the program using my IDE's debugger what I've seen is that for some reason valid coefficients are getting caught on the clause that I've marked with a "#" and the reference to the head of my list (the Term first variable) doesn't seem to be getting additional variables from the inputted string linked to it properly. Any help you can give would be much appreciated, thanks in advance. There are many required methods but this the relevant code for the problem I'm experiencing:

import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Polynomial 
{
// instance variables
private Term first;
private int numTerms;

/**
 * Constructor for objects of class Polynomial
 */
public Polynomial(String s)
{
    Pattern whiteSpace = Pattern.compile(" ");
    String[] poly = whiteSpace.split(s);
    double coefficient;
    int exponent;

    if(poly.length % 2 == 1) {
        throw new IllegalArgumentException();
    }

    first = new Term(); // dummy variable so that checking the first term specially is unnecessary

    for(int term = 0; term < poly.length; term += 2) {
        if(poly[term].matches("[\\-][0-9]||[0-9]||[0-9][\\.][0-9]||[\\-][0-9][\\.][0-9]")) {
            coefficient = Double.parseDouble(poly[term]);
            if(poly[term + 1].matches("[0-9]")) {
                exponent = Integer.parseInt(poly[term++]);
            } else {
                throw new IllegalArgumentException(); //#
            }

            numTerms++;
            this.addTerm(coefficient, exponent);
        }
    }
}
public void addTerm(double coef, int exp)
{
    if(coef == 0) {
        throw new IllegalArgumentException();
    }
    Term pointer = first; 
    while(pointer.next != null) { 
        if(exp == pointer.next.exponent) { 
            if(coef + pointer.next.coefficient == 0) {
                pointer.next = pointer.next.next; 
                numTerms--; 
            } else {
                pointer.next.coefficient += coef; 
                break; 
            }

        } else if(pointer.next.exponent < exp) { 
            Term newTerm = new Term(coef, exp, pointer.next.next); 
            pointer.next = newTerm; 
            numTerms++; 
            break; 
        }
        pointer = pointer.next;
    }
}
private class Term {
    double coefficient;
    int exponent;
    Term next;

    Term() {
        next = null;
    }

    Term(double coef, int exp, Term nextTerm) {
        coefficient = coef;
        exponent = exp;
        next = nextTerm;
    }
}`

Solution

  • You do not need regex to check for validity ParseXXX() takes care of that. If parsing fails, an Exception is thrown and then you can simply throw IllegalArgumentException

            for (int term = 0; term < poly.length - 1; term += 2) {
                try {
                    coefficient = Double.parseDouble(poly[term]);
                    exponent = Integer.parseInt(poly[term + 1]);
                    numTerms++;
                    this.addTerm(coefficient, exponent);
                } catch (NumberFormatException e) {
                    throw new IllegalArgumentException();
                }
            }
    

    Moreover, using regex = "[0-9]" means only a single digit exponent. You might want to change it to "[0-9]+"