Question

Write Java program. 3x^4^ + 2x^2^ + 3x + 7 added to 2x^3^ + 4x +...

Write Java program.

3x^4^ + 2x^2^ + 3x + 7 added to 2x^3^ + 4x + 5 is equal to 3x^4^ + 2x^3^ + 2x^2^ + 7x + 12.
Create an implementation of the ADT described above to create and add polynomials. Begin by defining a class Term that contains the exponent and coefficient. This class should implement the Comparable interface by comparing the values of the exponents. You should build a Polynomial class with a LinkedList<Term> instance variable, which specifically contains polynomial-related methods (like creating a polynomial, adding two polynomials, etc.). You need not build your own linked list, use the built in java.util.LinkedList.

Write a driver program to demonstrate your Polynomial ADT implementation, with a menu program that allows a user to:
edit the first polynomial (clear, create, and add terms)
edit the second polynomial (clear, create, and add terms)
display the result of adding the current first and second polynomial (without deleting/modifying those two polynomials)
exiting the program

The menu will allow the user to modify, clear, build, and add polynomials repeatedly until they choose to exit the program. Also, the user should be able to enter terms for a polynomial in whatever order they’d like (ex: 2x^2^ then 3x^5^ then 5x; or if have user enter it all at once as 5x + 2x^2^ + 3x^5^) and the polynomial should be stored, output, and maintain proper order (ex: 3x^5^ + 2x^2^ + 5x). You can assume the user will enter the terms/polynomials in whatever clear instructions you give them (extra credit for not assuming this and using exception handling).
For the ADT implementations (basically all classes but the driver, for this program) make sure to create all the required methods: setters, getters, toString, equals, constructors, etc.

Homework Answers

Answer #1

JAVA PROGRAM
===============================================
package polynomial;

import java.util.Scanner;

public class TestDriver {
  
   public static void main(String[] args){
       Scanner sc = new Scanner(System.in);
      
       Polynomial p1 = new Polynomial();
       Polynomial p2 = new Polynomial();
       Polynomial pAdd = null;
      
       do{
           printMenu();
           int option = Integer.parseInt(sc.nextLine());
           if(option ==4){
               System.out.println("Thank you!");
               System.exit(0);
           }else{
               if(option ==1){
                   editPolynomial(sc,p1);
               }else if(option ==2){
                   editPolynomial(sc,p2);
               }else if(option ==3){
                   if(p1!=null && p2!=null){
                       pAdd = p1.addPolynomial(p2);
                       System.out.println("Polynomial after addition is:"+ pAdd);
                   }
               }else{
                   System.out.println("Invalid option!");
                   sc.close();
               }
           }
       }while(true);
   }
  
   private static void printMenu(){
       System.out.println("1. Edit First Polynomial");
       System.out.println("2. Edit Second Polynomial");
       System.out.println("3. Add first polynomial with second");
       System.out.println("4. Exit");  
       System.out.println("Please enter your choice:");
   }
  
   private static void editPolynomial(Scanner sc,Polynomial p){
       System.out.println("1. Clear , 2. Create, 3. Add term, 4. display");
       System.out.println("Enter your option:");
       int editOption = Integer.parseInt(sc.nextLine());
       if(editOption==1){
           p.clear();
       }else if(editOption ==2){
           System.out.println("Enter polynomial string:");
           p.create(sc.nextLine());
       }else if(editOption ==3){
           System.out.println("Enter coeffcient for term:");
           int coeff = Integer.parseInt(sc.nextLine());
           System.out.println("Enter exponent for term:");
           int exp = Integer.parseInt(sc.nextLine());
           p.addTerm(coeff,exp);
       }else if(editOption ==4){
           System.out.println(p);
       }else{
           System.out.println("Invalid option!");
       }
   }

}

=============================================
package polynomial;

import java.util.Collections;
import java.util.LinkedList;

public class Polynomial {
   private LinkedList<Term> terms;
  
   public Polynomial(){
       this.terms = new LinkedList<Term>();
   }
  
   public Polynomial(String polynomial){
       this();
       create(polynomial);
   }
   public void clear(){
       terms.clear();
   }
  
   public void create(String polynomial){
       terms.clear();
       String[] polyTerms = null;
       if(polynomial!=null){
           polyTerms = polynomial.split("\\+");
       }
      
       int coeff,exp;
       if(polyTerms!=null){
           for(String poly: polyTerms){
               poly = poly.trim();
               if(poly.equals("x")){
                   coeff = 1;
                   exp =1;
               }else if(poly.contains("x")){
                   String[] data = poly.split("x");
                   coeff = Integer.parseInt(data[0]);
                   if(data.length ==1){ //for 3x,4x,...nx type of cases
                       exp = 1;
                   }else{
                       String expData = data[1];
                       String[] expDataArr = expData.split("\\^");
                       exp = Integer.parseInt(expDataArr[1]);
                   }
               }else{
                   coeff = Integer.parseInt(poly);
                   exp = 0;
               }
              
               addTerm(coeff, exp);
           }
       }
   }
  
   public void addTerm(Term term){
       this.terms.add(term);
   }
   public void addTerm(int coefficient,int exponent){
       if(coefficient!=0){
           boolean isFound = false;
           if(!terms.isEmpty()){
               for(int i = 0; i < terms.size(); i++){
                   Term term = terms.get(i);
                   if(term.getExponent() == exponent){
                       int updatedCoefficient = term.getCoefficient()+ coefficient;
                       terms.get(i).setCoefficient(updatedCoefficient);
                       isFound = true;
                       break;
                   }
               }
              
               if(!isFound){
                   terms.add(new Term(coefficient,exponent));
               }
           }else{
               terms.add(new Term(coefficient,exponent));
           }
       }
  
   }
  
   public Polynomial addPolynomial(Polynomial p){
       LinkedList<Term> terms1 = this.terms;
       LinkedList<Term> terms2 = p.terms;
       Polynomial pNew = new Polynomial();
       int coeff=0;
       boolean isAdded = false;
       LinkedList<Term> termsUsed = new LinkedList<Term>();
       for(Term t1: terms1){
           isAdded = false;
           for(Term t2: terms2){
               if(t2.getExponent() == t1.getExponent()){
                   coeff = t1.getCoefficient()+t2.getCoefficient();
                   termsUsed.add(t2);
                   isAdded = true;
                   break;
               }
           }
          
           if(isAdded){
               if(coeff!=0)
                   pNew.addTerm(new Term(coeff,t1.getExponent()));
           }else{
               pNew.addTerm(t1);
           }
          
       }
      
       for(Term t2: terms2){
           if(!termsUsed.contains(t2)){
               pNew.addTerm(t2);
           }
       }
      
      
       return pNew;  
      
   }

   @Override
   public String toString() {
      
       StringBuilder sb = new StringBuilder();      
       if(!terms.isEmpty()){
           Collections.sort(terms);
           int counter = 0;
           for(Term term: terms){
               counter++;
               String currentTermStr="";
               int coeff = term.getCoefficient();
               int exp = term.getExponent();
              
               if(coeff>0){
                   if(counter > 1)
                       currentTermStr=currentTermStr+"+";
                   if(coeff>1)
                       currentTermStr=currentTermStr+coeff;
               }else if(coeff < -1){
                   currentTermStr=currentTermStr+coeff;
               }
              
               if(exp>0){
                   currentTermStr = currentTermStr +"x";
                   if(exp >1){
                       currentTermStr = currentTermStr+"^"+exp+"^";
                   }
               }
              
               sb.append(currentTermStr);
           }
       }
      
       return sb.toString();
   }
  
  
}

===========================================
package polynomial;

public class Term implements Comparable<Term>{
  
   private int exponent;
   private int coefficient;
  
   public Term( int coefficient,int exponent) {
       this.exponent = exponent;
       this.coefficient = coefficient;
   }
  
  
   @Override
   public int compareTo(Term term) {
       if(this.exponent < term.exponent){
           return 1;
       }else if(this.exponent > term.exponent){
           return -1;
       }else{
           return 0;
       }
   }
   @Override
   public String toString() {
       return coefficient+"x^"+exponent+"^";
   }
  
  


   public int getExponent() {
       return exponent;
   }


   public int getCoefficient() {
       return coefficient;
   }


   public void setExponent(int exponent) {
       this.exponent = exponent;
   }


   public void setCoefficient(int coefficient) {
       this.coefficient = coefficient;
   }

   @Override
   public boolean equals(Object obj) {
       Term t = (Term)obj;
      
       if(this.coefficient == t.coefficient && this.exponent==t.exponent){
           return true;
       }
      
       return false;
   }
  

}

======================================
output
======================================
1. Edit First Polynomial
2. Edit Second Polynomial
3. Add first polynomial with second
4. Exit
Please enter your choice:
1
1. Clear , 2. Create, 3. Add term, 4. display
Enter your option:
2
Enter polynomial string:
3x^4^+2x^2^+3x+7
1. Edit First Polynomial
2. Edit Second Polynomial
3. Add first polynomial with second
4. Exit
Please enter your choice:
1
1. Clear , 2. Create, 3. Add term, 4. display
Enter your option:
4
3x^4^+2x^2^+3x+7
1. Edit First Polynomial
2. Edit Second Polynomial
3. Add first polynomial with second
4. Exit
Please enter your choice:
2
1. Clear , 2. Create, 3. Add term, 4. display
Enter your option:
3
Enter coeffcient for term:
2
Enter exponent for term:
4
1. Edit First Polynomial
2. Edit Second Polynomial
3. Add first polynomial with second
4. Exit
Please enter your choice:
2
1. Clear , 2. Create, 3. Add term, 4. display
Enter your option:
3
Enter coeffcient for term:
3
Enter exponent for term:
1
1. Edit First Polynomial
2. Edit Second Polynomial
3. Add first polynomial with second
4. Exit
Please enter your choice:
2
1. Clear , 2. Create, 3. Add term, 4. display
Enter your option:
4
2x^4^+3x
1. Edit First Polynomial
2. Edit Second Polynomial
3. Add first polynomial with second
4. Exit
Please enter your choice:
3
Polynomial after addition is:5x^4^+2x^2^+6x+7
1. Edit First Polynomial
2. Edit Second Polynomial
3. Add first polynomial with second
4. Exit
Please enter your choice:
4
Thank you!


Know the answer?
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
Similar Questions
Write a program in Java that: 1. will prompt user with a menu that contains options...
Write a program in Java that: 1. will prompt user with a menu that contains options to: a. Add a To-Do Item to a todo list. A To-Do Item contains: i. An arbitrary reference number (4; 44,004; etc.) ii. A text description of the item ("Pick up dry cleaning", etc.) iii. A priority level (1, 2, 3, 4, or 5) b. View an item in the list (based on its reference number) c. Delete an item from the list (based...
Problem Statement: Write a Java program “HW6_lastname.java” that prints a program title and a menu with...
Problem Statement: Write a Java program “HW6_lastname.java” that prints a program title and a menu with four items. The user should then be prompted to make a selection from the menu and based on their selection the program will perform the selected procedure. The title and menu should be as the following: Student name: <your name should be printed> CIS 232 Introduction to Programming Programming Project 6 Due Date: October 23, 2020 Instructor: Dr. Lomako ******************************** 1.     Compute Angles                               *...
Objective: Write a Java program that will use a JComboBox from which the user will select...
Objective: Write a Java program that will use a JComboBox from which the user will select to convert a temperature from either Celsius to Fahrenheit, or Fahrenheit to Celsius. The user will enter a temperature in a text field from which the conversion calculation will be made. The converted temperature will be displayed in an uneditable text field with an appropriate label. Specifications Structure your file name and class name on the following pattern: The first three letters of your...
**JAVA LANGUAGE** Write a program that models an employee. An employee has an employee number, a...
**JAVA LANGUAGE** Write a program that models an employee. An employee has an employee number, a name, an address, and a hire date. A name consists of a first name and a last name. An address consists of a street, a city, a state (2 characters), and a 5-digit zip code. A date consists of an integer month, day and year. All fields are required to be non-blank. The Date fields should be reasonably valid values (ex. month 1-12, day...
In c++ create a class to maintain a GradeBook. The class should allow information on up...
In c++ create a class to maintain a GradeBook. The class should allow information on up to 3 students to be stored. The information for each student should be encapsulated in a Student class and should include the student's last name and up to 5 grades for the student. Note that less than 5 grades may sometimes be stored. Your GradeBook class should at least support operations to add a student record to the end of the book (i.e., the...
Project 2 statement Please write this in JAVA. Please read this entire statement carefully before you...
Project 2 statement Please write this in JAVA. Please read this entire statement carefully before you start doing anything… This project involves implementing a simple university personnel management program. The program contains two different kinds of objects: students and faculty. For each object, the program stores relevant information such as university ID, name, etc. Different information is stored depending on the type of the object. For example, a student has a GPA, while a faculty has a title and department...
IN PYTHON Menu: 1. Hotdog. ($2) 2. Salad ($3)  3. Pizza ($2) 4.Burger ($4) 5.Pasta ($7) Write...
IN PYTHON Menu: 1. Hotdog. ($2) 2. Salad ($3)  3. Pizza ($2) 4.Burger ($4) 5.Pasta ($7) Write a menu-driven program for  Food Court. (You need to use functions!) Display the food menu to a user . 5 options Use numbers for the options and for example "6" to exit. Ask the user what he/she wants and how many of it. (Check the user inputs) AND use strip() function to strip your inputs(if needed) Keep asking the user until he/she chooses the exit...
I need the java code for a 4-function calculator app on android studio. Please make sure...
I need the java code for a 4-function calculator app on android studio. Please make sure all the requirements shown below are followed (such as the error portion and etc). The topic of this app is to simply create a 4 function calculator which calculates math expressions (add, subtract, multiply, and divide numbers). The requirements are the following : - The only buttons needed are 0-9, *, /, +, -, a clear, and enter button - Implement the onclicklistener on...
This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program). Extend...
This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program). Extend the ItemToPurchase class per the following specifications              Private fields string itemDescription - Initialized in default constructor to "none" Parameterized constructor to assign item name, item description, item price, and itemquantity (default values of 0).             Public instance member methods setDescription() mutator & getDescription() accessor (2 pts) printItemCost() - Outputs the item name followed by the quantity, price, and subtotal printItemDescription() - Outputs the...
Using C++, Python, or Java, write a program that: In this programming exercise you will perform...
Using C++, Python, or Java, write a program that: In this programming exercise you will perform an empirical analysis of the QuickSort algorithm to study the actual average case behavior and compare it to the mathematically predicted behavior. That is, you will write a program that counts the number of comparisons performed by QuickSort on an array of a given size. You will run the program on a large number of arrays of a certain size and determine the average...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT