Question

I need help filling in the the code in the methods add, multiply, and evaluate package...

I need help filling in the the code in the methods add, multiply, and evaluate

package poly;

import java.io.IOException;
import java.util.Scanner;

/**
* This class implements evaluate, add and multiply for polynomials.
*
*
*
*/
public class Polynomial {
  
   /**
   * 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 sc Scanner from which a polynomial is to be read
   * @throws IOException If there is any input error in reading the polynomial
   * @return The polynomial linked list (front node) constructed from coefficients and
   * degrees read from scanner
   */
   public static Node read(Scanner sc)
   throws IOException {
       Node poly = null;
       while (sc.hasNextLine()) {
           Scanner scLine = new Scanner(sc.nextLine());
           poly = new Node(scLine.nextFloat(), scLine.nextInt(), poly);
           scLine.close();
       }
       return poly;
   }
  
   /**
   * Returns the sum of two polynomials - DOES NOT change either of the input polynomials.
   * The returned polynomial MUST have all new nodes. In other words, none of the nodes
   * of the input polynomials can be in the result.
   *
   * @param poly1 First input polynomial (front of polynomial linked list)
   * @param poly2 Second input polynomial (front of polynomial linked list
   * @return A new polynomial which is the sum of the input polynomials - the returned node
   * is the front of the result polynomial
   */
   public static Node add(Node poly1, Node poly2) {
       /** COMPLETE THIS METHOD **/
       // FOLLOWING LINE IS A PLACEHOLDER TO MAKE THIS METHOD COMPILE
       // CHANGE IT AS NEEDED FOR YOUR IMPLEMENTATION
       return null;
   }
  
   /**
   * Returns the product of two polynomials - DOES NOT change either of the input polynomials.
   * The returned polynomial MUST have all new nodes. In other words, none of the nodes
   * of the input polynomials can be in the result.
   *
   * @param poly1 First input polynomial (front of polynomial linked list)
   * @param poly2 Second input polynomial (front of polynomial linked list)
   * @return A new polynomial which is the product of the input polynomials - the returned node
   * is the front of the result polynomial
   */
   public static Node multiply(Node poly1, Node poly2) {
       /** COMPLETE THIS METHOD **/
       // FOLLOWING LINE IS A PLACEHOLDER TO MAKE THIS METHOD COMPILE
       // CHANGE IT AS NEEDED FOR YOUR IMPLEMENTATION
       return null;
   }
      
   /**
   * Evaluates a polynomial at a given value.
   *
   * @param poly Polynomial (front of linked list) to be evaluated
   * @param x Value at which evaluation is to be done
   * @return Value of polynomial p at x
   */
   public static float evaluate(Node poly, float x) {
       /** COMPLETE THIS METHOD **/
       // FOLLOWING LINE IS A PLACEHOLDER TO MAKE THIS METHOD COMPILE
       // CHANGE IT AS NEEDED FOR YOUR IMPLEMENTATION
       return 0;
   }
  
   /**
   * Returns string representation of a polynomial
   *
   * @param poly Polynomial (front of linked list)
   * @return String representation, in descending order of degrees
   */
   public static String toString(Node poly) {
       if (poly == null) {
           return "0";
       }
      
       String retval = poly.term.toString();
       for (Node current = poly.next ; current != null ;
       current = current.next) {
           retval = current.term.toString() + " + " + retval;
       }
       return retval;
   }  
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.io.IOException;
import java.util.Scanner;

class Term { 
    public float coeff; 
    public int degree; 
    public Term(float coeff, int degree) { 
        this.coeff = coeff; this.degree = degree; 
    } 
    public boolean equals(Object other) { 
        return other != null && other instanceof Term && coeff == ((Term)other).coeff && degree == ((Term)other).degree; 
    }

    public String toString() {
        if (degree == 0) {
            return coeff + ""; 
        } else if (degree == 1) {
            return coeff + "x"; 
        } else {
            return coeff + "x^" + degree; 
        } 
    }
}


class Node{
    Term term; 
    Node next; 
    public Node(float coeff, int degree, Node next) { 
        term = new Term(coeff, degree); this.next = next; 
    } 
}

public class Polynomial {

    /**
     * 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 sc Scanner from which a polynomial is to be read
     * @throws IOException If there is any input error in reading the polynomial
     * @return The polynomial linked list (front node) constructed from coefficients
     *         and degrees read from scanner
     */
    public static Node read(Scanner sc) throws IOException {
        Node poly = null;
        while (sc.hasNextLine()) {
            Scanner scLine = new Scanner(sc.nextLine());
            poly = new Node(scLine.nextFloat(), scLine.nextInt(), poly);
            scLine.close();
        }
        return poly;
    }

    /**
     * Returns the sum of two polynomials - DOES NOT change either of the input
     * polynomials. The returned polynomial MUST have all new nodes. In other words,
     * none of the nodes of the input polynomials can be in the result.
     *
     * @param poly1 First input polynomial (front of polynomial linked list)
     * @param poly2 Second input polynomial (front of polynomial linked list
     * @return A new polynomial which is the sum of the input polynomials - the
     *         returned node is the front of the result polynomial
     */
    public static Node add(Node poly1, Node poly2) {
        Node poly = null;

        Node p1 = poly1;
        while (p1 != null) {
            poly = addTerm(poly, p1.term.coeff, p1.term.degree);
            p1 = p1.next;
        }
        Node p2 = poly2;
        while (p2 != null) {
            poly = addTerm(poly, p2.term.coeff, p2.term.degree);
            p2 = p2.next;
        }

        return poly;
    }

    /**
     * Returns the product of two polynomials - DOES NOT change either of the input
     * polynomials. The returned polynomial MUST have all new nodes. In other words,
     * none of the nodes of the input polynomials can be in the result.
     *
     * @param poly1 First input polynomial (front of polynomial linked list)
     * @param poly2 Second input polynomial (front of polynomial linked list)
     * @return A new polynomial which is the product of the input polynomials - the
     *         returned node is the front of the result polynomial
     */
    public static Node multiply(Node poly1, Node poly2) {
        Node poly = null;

        while(poly1.next != null) {

            Node start = poly2;
            while(start != null) {
                poly = addTerm(poly, poly1.term.coeff * start.term.coeff, 
                        poly1.term.degree + start.term.degree);
                start = start.next;
            }

            poly1 = poly1.next;
        }

        return poly;
    }

    // helper method to add a node in already existing list
    // The passed list poly is modified
    private static Node addTerm(Node poly, float coeff, int degree) {
        if(coeff == 0)
            return poly;

        // create node
        Node n = new Node(coeff, degree, null);

        // if it is the first element
        if (poly == null) {
            return n;
        } else {

            // if it has same exponent as head
            if (poly.term.degree == degree) {
                poly.term.coeff = (poly.term.coeff + coeff);
                return poly;
            } else if (poly.term.degree < degree) {
                // it need to be inserted before head
                n.next = poly;
                poly = n;
                return poly;
            }

            Node p = poly;
            while (p.next != null) {

                if (degree == p.term.degree) {
                    // if same exponent term is there
                    p.term.coeff = (p.term.coeff + coeff);
                    return poly;
                } else if (degree > p.next.term.degree) {
                    // loop till we get some lower exponent position
                    n.next = p.next;
                    p.next = n;
                    return poly;
                }

                // move to next
                p = p.next;
            }

            if(p.term.degree == degree) {
                p.term.coeff = (p.term.coeff + coeff);
                return poly;
            }

            // add to the last
            p.next = n;
            return poly;
        }
    }

    /**
     * Evaluates a polynomial at a given value.
     *
     * @param poly Polynomial (front of linked list) to be evaluated
     * @param x    Value at which evaluation is to be done
     * @return Value of polynomial p at x
     */
    public static float evaluate(Node poly, float x) {
        float result = 0;

        while(poly != null) {
            result += poly.term.coeff * Math.pow(x, poly.term.degree);
            poly = poly.next;
        }

        return result;
    }

    /**
     * Returns string representation of a polynomial
     *
     * @param poly Polynomial (front of linked list)
     * @return String representation, in descending order of degrees
     */
    public static String toString(Node poly) {
        if (poly == null) {
            return "0";
        }

        String retval = poly.term.toString();
        for (Node current = poly.next; current != null; current = current.next) {
            retval = current.term.toString() + " + " + retval;
        }
        return retval;
    }
}

Please upvote, as i have given the exact answer as asked in question. Still in case of any concerns in code, let me know in comments. Thanks!

Add a comment
Know the answer?
Add Answer to:
I need help filling in the the code in the methods add, multiply, and evaluate package...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In Java You may add any classes or methods to the following as you see fit in order to complete t...

    In Java You may add any classes or methods to the following as you see fit in order to complete the given tasks. Modify the LinkedList (or DoubleLinkedList) class and add a method append. append should take another LinkedList (DoubleLinkedList) as input and append that list to the end of this list. The append method should work by doing a few "arrow" adjustments on the boxes and it should not loop through the input list to add elements one at...

  • JAVA you have been given the code for Node Class (that holds Strings) and the LinkedList...

    JAVA you have been given the code for Node Class (that holds Strings) and the LinkedList Class (some methods included). Remember, you will use the LinkedList Class that we developed in class not Java’s LinkedList Class. You will add the following method to the LinkedList Class: printEvenNodes – this is a void method that prints Nodes that have even indices (e.g., 0, 2, 4, etc). Create a LinkedListDemo class. Use a Scanner Class to read in city names and store...

  • Inventory (linked lists: insert at the front of a list)

    import java.util.Scanner;public class Inventory {   public static void main (String[] args) {      Scanner scnr = new Scanner(System.in);             InventoryNode headNode;                                                    InventoryNode currNode;      InventoryNode lastNode;      String item;      int numberOfItems;      int i;      // Front of nodes list           ...

  • Java/LinkedList Need help with a few of the TODO parts, more info below in comments in...

    Java/LinkedList Need help with a few of the TODO parts, more info below in comments in bold. Thanks, package lab4; import java.util.IdentityHashMap; public class IntNode implements Cloneable {    private int data;    private IntNode next;       public IntNode(int d, IntNode n) {        data = d;        next = n;    }       public IntNode getNext() {        return next;    }          /// Override methods from Object       @Override   ...

  • Grocery shopping list (linked list: inserting at the end of a list)

    import java.util.Scanner;public class ShoppingList {   public static void main (String[] args) {      Scanner scnr = new Scanner(System.in);      ItemNode headNode;  // Create intNode objects                                                         ItemNode currNode;      ItemNode lastNode;      String item;      int i;      // Front of nodes list           ...

  • Here is the IntegerLinkedList_incomplete class: public class IntegerLinkedList { static class Node { /** The element...

    Here is the IntegerLinkedList_incomplete class: public class IntegerLinkedList { static class Node { /** The element stored at this node */ private int element; // reference to the element stored at this node /** A reference to the subsequent node in the list */ private Node next; // reference to the subsequent node in the list /** * Creates a node with the given element and next node. * * @param e the element to be stored * @param n...

  • Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements...

    Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements DoubleEndedList { private Node front; // first node in list private Node rear; // last node in list private int size; // number of elements in list ////////////////////////////////////////////////// // YOU MUST IMPLEMENT THE LOCATE METHOD BELOW // ////////////////////////////////////////////////// /** * Returns the position of the node containing the given value, where * the front node is at position zero and the rear node is...

  • Data Structures - Singly Linked Lists You will add a method swapNodes to SinglyLinkedList class (below). This method should swap two nodes node1 and node2 (and not just their contents) given reference...

    Data Structures - Singly Linked Lists You will add a method swapNodes to SinglyLinkedList class (below). This method should swap two nodes node1 and node2 (and not just their contents) given references only to node1 and node2. The new method should check if node1 and node2 are the same node, etc. Write the main method to test the swapNodes method. You may need to traverse the list. package linkedlists; public class SinglyLinkedList<E> implements Cloneable {    // ---------------- nested Node class...

  • Java - I need help creating a method that removes a node at the specific index...

    Java - I need help creating a method that removes a node at the specific index position. The * first node is index 0. public boolean delAt(int index) { src code 2 different classes ******************************************** public class Node { private String data; private Node next; public Node(String data, Node next) { this.data = data; this.next = next; } public Node() { } public String getData() { return data; } public void setData(String data) { this.data = data; } public void...

  • Java StringNode Case Study: Rewrite the following methods in the StringNode class shown below. Leave all...

    Java StringNode Case Study: Rewrite the following methods in the StringNode class shown below. Leave all others intact and follow similar guidelines. The methods that need to be changed are in the code below. - Rewrite the indexOf() method. Remove the existing recursive implementation of the method, and replace it with one that uses iteration instead. - Rewrite the isPrefix() method so that it uses iteration. Remove the existing recursive implementation of the method, and replace it with one that...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT