I need some help with my assignment in Java... I need to write a program that prints out and calculates polynomials. Full description in question
Question 3 Look at the attached Polynomial class, which models a single variable, multi-term function with integer exponents and coefficients. When the class is first constructed, the polynomical has no terms. New terms are added using the addTerm(coefficient, exponent) method. Extend the class by adding two methods: public double evaluate ( int x ) public String toString () The evaluate method will calculate the value of P(x), that is, the value of the sum of the terms when a value is substituted for x. You will be penalised for the use of the Math.pow() function - it is possible to calculate the value of the terms using only loops and multiplication or division. The toString method returns a String representation of the polynomial, for example: P(x) = 2x^4 + 1x^3 + 6x^2 - 6x^-1 Terms should be ordered from highest exponent to lowest. Three private methods have been written to help you create the evaluate and toString methods: getHighestExponent returns the value of the highest exponent in the polynomial getLowestExponent returns the value of the lowest exponent getCoefficient(int exponent) returns the coefficient of the term with the exponent specified. Your code does not need to access the terms instance variable in the Polynomial class yourself. These three methods should be sufficient to allow you to write the two new methods required. Note that as terms are added using the addTerm method, if more than one term with the same exponent is added, the terms are automatically added together. This should underline the importance of accessing the data in the class only through the existing methods. Once you have added the methods, create a driver class called Question3. This class should contain a main method that prompts the user to add terms to the polynomial until they are done, outputting the String representation of the function after each change. Once the user has finished adding terms, prompt the user for a value to assign to x and evaluate the function using this value. Print the results.
I have written the "evaluate" method, but need help with the toString
Sample I/O: **** Polynomial Calculator ***** Enter term exponent: 2 Enter term coefficient: 1 Polynomial is now: P(x) = x^2 Would you like to add another term? (y/n) y Enter term exponent: 2 Enter term coefficient: 1 Polynomial is now: P(x) = 2x^2 Would you like to add another term? (y/n) y Enter term exponent: 1 Enter term coefficient: 3 Polynomial is now: P(x) = 2x^2 + 3x Would you like to add another term? (y/n) y Enter term exponent: 0 Enter term coefficient: -4 Polynomial is now: P(x) = 2x^2 + 3x - 4 Would you like to add another term? (y/n) n Enter value for X 14 P(14) = 430.0
Join our real-time social learning platform and learn together with your friends!