Hello below is my code for a program that reads in integers rom keyboard input and creates two polynomials from that input and then does some maths functions on them.
I've got the addition working, having trouble with the multiplication though.
Any help would be appreciated.

thanks

    import java.util.*;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.text.*;
    import java.io.IOException;
    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.Scanner;


    public class Polynomial
    {
       private Monomial head;
       private int TOLERANCE = 0;





    /******************  the  Monomial (inner) class   ********************************/

       private class Monomial
       {
          private DecimalFormat precision = new DecimalFormat("#.####");
          private int deg;     // degree of polynomial
          private int coeff; // coefficients
          private Monomial next; // Pointer to next term


          public Monomial(int coeff, int deg, Monomial next)
          {
             this.coeff = coeff;    //coefficient
             this.deg = deg;        // Degree
             this.next = next;      // Pointer
          }
          public String toString()
          {
             String form = precision.format(Math.abs(coeff));

             if(deg == 0) return form ;
             else
             if(deg == 1) return form + "x";
             else
             return form +"x^" + deg;
          }
          public boolean equals(Monomial mono)
          {
             return coeff == mono.coeff && deg == mono.deg;
          }

       }

    //*********************************************************************************************

       public Polynomial()
       {
          head = null;
       }

     /***************************************************************************
       *  Adds a new term into the polynomial, assuming that the polynomial
       *  is sorted in order from smallest to largest exponent.
     **************************************************************************/
       public void addTerm(int coeff, int deg)
       {
          if( Math.abs(coeff) < TOLERANCE ) return;

          if( head == null || deg < head.deg )
          {
             head = new Monomial(coeff, deg, head);
             return;
          }

          Monomial cur = head;
          Monomial prev = null;

          while( cur != null && deg > cur.deg)
          {
             prev = cur;
             cur = cur.next;
          }
          if( cur == null || deg != cur.deg )
                prev.next = new Monomial(coeff, deg, cur);
          else
          {
             cur.coeff += coeff;
             if( Math.abs(cur.coeff) < TOLERANCE )
               if(prev != null)
                   prev.next = cur.next;
                else
                   head = head.next;
          }
       }

       public String toString()
       {
          StringBuffer sb = new StringBuffer();

          for(Monomial tmp = head; tmp != null; tmp = tmp.next)
            if(tmp.coeff < 0 )
               sb.append(" - " + tmp.toString());
            else
               sb.append(" + " + tmp.toString());

          return sb.toString();
       }

    //*********************************************************************************************


    /*********************************************************************************************

       *  Return the degree of this polynomial

     **********************************************************************************************/



    //*********************************************************************************************/



    /*********************************************************************************************
       *  Multiplies Polynomial 1 to Polynomial 2
       *  The method does not change the original polynomial.
    **********************************************************************************************/





    //*********************************************************************************************/

    /*********************************************************************************************
       *  Adds Polynomial 1 to Polynomial 2
       *  The method does not change the original polynomial.
    **********************************************************************************************/
       public Polynomial add(Polynomial poly)
       {
          Polynomial res = clone();

          for(Monomial tmp = poly.head; tmp != null; tmp = tmp.next)
             res.addTerm(tmp.coeff, tmp.deg);

          return res;
       }

       public Polynomial clone()
       {
          Polynomial res = new Polynomial();

          for(Monomial tmp = head; tmp != null; tmp = tmp.next)
             res.addTerm(tmp.coeff, tmp.deg);

          return res;
       }

       public boolean equals(Polynomial poly)
       {
          Monomial tmp1 = head;
          Monomial tmp2 = poly.head;

          while(tmp1 != null && tmp2 != null)
          {
             if( !tmp1.equals(tmp2) ) return false;
             tmp1 = tmp1.next;
             tmp2 = tmp2.next;
          }
          return true;
       }

    //*********************************************************************************************/


    /*********************************************************************************************
       *  Multiplies by a Constant
       *  The method does not change the original polynomial.
    **********************************************************************************************/

       public Polynomial multiply(int num)
       {
          Polynomial res = clone();

          for(Monomial tmp = res.head; tmp != null; tmp = tmp.next)
             tmp.coeff *= num;

          return res;
       }

    //*********************************************************************************************/


     /*********************************************************************************************
       *  Returns a new polynomial that is the derivative of this polynomial.
     **********************************************************************************************/
       public Polynomial diff()
       {
          Polynomial res = new Polynomial();

          for(Monomial tmp = head; tmp != null; tmp = tmp.next)
          {
             if(tmp.deg != 0)
                res.addTerm(tmp.coeff * tmp.deg, tmp.deg - 1 );
          }

          return res;
       }

    //*********************************************************************************************/


     /*********************************************************************************************
       *  Returns a new polynomial that is the result of Monomial times polynomial.
       **  The method does not change the original polynomial.
     **********************************************************************************************/
    /*
    public Polynomial times(Polynomial poly)
       {
              {
          Polynomial result = new Polynomial();



             for(Monomial tmp2 = poly.head; tmp2 != null; tmp2 = tmp2.next)
             res.addTerm(tmp2.coeff, tmp2.deg );


             for(Monomial tmp = head; tmp != null; tmp = tmp.next)
             res.addTerm(tmp.coeff, tmp.deg);

          while(tmp != null && tmp2 != null)
          {
             result.addTerm(tmp.coeff * tmp2.coeff, tmp.deg + tmp2.deg);
             tmp = tmp.next;
             tmp2 = tmp2.next;
          }
          return result;


       }

       }
    */





    //*********************************************************************************************/




     /*********************************************************************************************
       *  Driver Program to Test Polynomial Class
     **********************************************************************************************/

       public static void main(String[] args)

       {

    //---------------- Code to chose between keyboard input or file input------------------------


          System.out.println("If you would like you enter the polynomial via a text file 'Polyinput.txt' PRESS 

    1. ");
          System.out.println("If you would like you enter the polynomial via the keyboard, PRESS ANY OTHER 

    INTEGER... ");
          Scanner inputquestion=new Scanner(System.in);
          System.out.print("Enter Option: "); // Prompts for selection choice
          int option=inputquestion.nextInt(); // Stores input in option

            if (option == 1) // if loop to jump into read from text file
            {



    //--------------  Read Input from File.------------------------------------------------------------


            String content = new String();
            String name = new String();
            File file = new File("polyinput.txt");
            LinkedList<String> list = new LinkedList<String>();

            try {
                Scanner sc = new Scanner(new FileInputStream(file));
                    while (sc.hasNext()) {
                    name = sc.next();
                    content = sc.nextLine();
                    list.add(content);

                }

                sc.close();
            } catch (FileNotFoundException fnfe) {
                fnfe.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("\nProgram terminated Safely...");
            }

            Iterator<String> i = list.iterator();
            while (i.hasNext()) {
                System.out.println(name + i.next() + "\n");

            }


        } //------------ End if to enter input text file code---------------------------------------




        else  //--------------start of else for keyboard input--------------------------------------
        {

        //------- Code to Prompt for Polynomial 1 

    -----------------------------------------------------------------


          Polynomial polynomial1 = new Polynomial();
          System.out.println( );
          System.out.println( );
          System.out.println("Enter first Polynomial");
          System.out.println("(Enter Zero (0) as Exponent value to move to second Polynomial");
          System.out.println( );

          //Insert do while loop exponent not equal 0
         int ExponentTest = 1;
          do {

          Scanner inputCoefficent=new Scanner(System.in);
          System.out.print("Enter Coefficient: "); // Prompts for coefficent
          int Coefficient=inputCoefficent.nextInt(); // Stores coefficent in coefficent
          Scanner inputExponent=new Scanner(System.in);
          System.out.print("Enter Exponent: "); // Prompts for Exponent
          int Exponent=inputExponent.nextInt(); // Stores Exponent in Exponent

            if (Exponent < 1)
              {
                ExponentTest = 0;
              }


          polynomial1.addTerm(Coefficient, Exponent);

           } while (ExponentTest > 0);
            // ------ end do while loop ---------------

          System.out.println( );
          System.out.println( " Entered Polynomial is: " + polynomial1 );


    //----------------------------------------------------------------------------------------------------------

    //----------- Code to Prompt for Polynomial 2 -----------------------------------------------------------------

          Polynomial polynomial2 = new Polynomial();
          System.out.println( );
          System.out.println( );
          System.out.println("Enter second Polynomial");
          System.out.println("(Enter Zero (0) as Exponent value to complete Polynomial");
          System.out.println( );

          //Insert do while loop exponent not equal 0
         int ExponentTest2 = 1;
          do {

          Scanner inputCoefficent=new Scanner(System.in);
          System.out.print("Enter Coefficient: "); // Prompts for coefficent
          int Coefficient=inputCoefficent.nextInt(); // Stores coefficent in coefficent
          Scanner inputExponent=new Scanner(System.in);
          System.out.print("Enter Exponent: "); // Prompts for Exponent
          int Exponent=inputExponent.nextInt(); // Stores Exponent in Exponent

            if (Exponent < 1)
              {
                ExponentTest2 = 0;
              }


          polynomial2.addTerm(Coefficient, Exponent);

           } while (ExponentTest2 > 0);
            // ------ end do while loop ---------------

          System.out.println( );
          System.out.println( " Entered Polynomial is: " + polynomial2 );

    //----------------------------------------------------------------------------------------------------------


    //------- Code to Prompt for Monomial (ax^k) to multiply both Polynomials by---------------------------------

          Polynomial monomial1 = new Polynomial();
          System.out.println( );
          System.out.println( );
          System.out.println("Enter details for the Monomial equation");
          Scanner inputMonomial=new Scanner(System.in);
                System.out.print("Enter Coefficent: "); //Prompts for Coefficient
                int num1=inputMonomial.nextInt(); // Stores Coefficient in num1
                System.out.print("Enter Exponent: "); // Prompts for Exponent
                int num2=inputMonomial.nextInt(); //Stores Exponenent in num2
                monomial1.addTerm(num1, num2); // Creates the Monomial equation

            System.out.println();
            System.out.println( "Monomial: " );
            System.out.println( monomial1 );
            System.out.println( );

    //----------------------------------------------------------------------------------------------------

    //------- Code to Prompt for constant to multiply by and then reads in the constant and stores in Constant1

          System.out.println("Enter integer to be used as the constant");
          Scanner inputConstant=new Scanner(System.in);
          System.out.print("Enter Constant: "); // Prompts for constant
          int Constant1=inputConstant.nextInt(); // Stores Constant in Constant1

          System.out.println( "Constant used to multiply polynomials: " );
          System.out.println( Constant1 );
          System.out.println( );

    //----------------------------------------------------------------------------------------------------------


    //------------------------ Returns display for operations onto the screen-----------------------------------


          System.out.println( );
          System.out.println( "Degree of Polynomial 1 ("+ polynomial1 + "): " /*+ polynomial1.degree()*/);


          System.out.println( );
          System.out.println( "Degree of Polynomial 2 ("+ polynomial2 + "): " );

          System.out.println( );
          System.out.println( "Multiply Polynomial 1 ("+ polynomial1 + ") by Polynomial 2 ("+ polynomial2 + "): " );

          System.out.println( );
          System.out.println( "Multiply Polynomial 1 ("+ polynomial1 + ") by Monomial ("+ monomial1 + "): " );
          Polynomial MultiplyMonomialResult1 = polynomial1.add(monomial1);
          System.out.println( monomial1 + " * " + polynomial1 + " = " + MultiplyMonomialResult1 );
          System.out.println( );

          System.out.println( );
          System.out.println( "Multiply Polynomial 2 ("+ polynomial2 + ") by Monomial ("+ monomial1 + "): " );
          Polynomial MultiplyMonomialResult2 = polynomial2.add(monomial1);
          System.out.println( monomial1 + " * " + polynomial2 + " = " + MultiplyMonomialResult2 );
          System.out.println( );

          System.out.println( );
          System.out.println( "Polynomial 1 (" + polynomial1 + ") plus Polynomial 2 (" + polynomial2 + "): " );
          Polynomial AdditionResult = polynomial1.add(polynomial2);
          System.out.println( polynomial1 );
          System.out.println( polynomial2 );
          System.out.println( "=" );
          System.out.println( AdditionResult );
          System.out.println( );

          System.out.println( "multiply Polynomial 1 ("+ polynomial1 + ") by constant entered into console (ie " + 

    Constant1 + "): " );
          Polynomial MultiplyConstant1 = polynomial1.multiply(Constant1);
          System.out.println( Constant1 + " * " + polynomial1 + " = " + MultiplyConstant1 );
          System.out.println( );

          System.out.println( "multiply Polynomial 2 ("+ polynomial2 + ") by constant entered into console (ie " + 

    Constant1 + "): " );
          Polynomial MultiplyConstant2 = polynomial2.multiply(Constant1);
          System.out.println( Constant1 + " * " + polynomial2 + " = " + MultiplyConstant2 );
          System.out.println( );

          System.out.println( "Derivative of Polynomial 1: " );
          Polynomial diffresult1 = polynomial1.diff();
          System.out.println( "Polynomial 1: " + polynomial1 );
          System.out.println( "Derivative =  " + diffresult1 );
          System.out.println( );

          System.out.println( "Derivative of Polynomial 2" );
          Polynomial diffresult2 = polynomial2.diff();
          System.out.println( "Polynomial 2: " + polynomial2 );
          System.out.println( "Derivative =  " + diffresult2 );
          System.out.println( );

    //-------------------------------End Screen output of operations for keyboard entry-------------------------

    } // End of else for keyboard input.------------------------------------------------------------------------


       }
    }

Recommended Answers

All 7 Replies

You should post only relevant part where you have trouble.

it's gonna be hard to tell which part of the code shows where the multiplication has gone awry
could you post the current output and then post what it should look like

Cheers.
I have been working on this since i posted it and yes realise i prob shouldnt have posted the whole massive chunk at once.

problem i have now is that it is only multiplying polynomial 1 by the first term of polynomial 2

so 2x + 2 * 5x + 5 = 10x2 + 10x

instead of 10x2 + 20x + 10

and here is the code that does the multiplication:

   public Polynomial multiply(Polynomial poly)
   {
      Polynomial res = clone();

      for(Monomial tmp = res.head; tmp != null; tmp = tmp.next)
         res.addTerm(tmp.coeff *= poly.head.coeff, tmp.deg += poly.head.deg);

         double num = 0.5;
         for(Monomial tmp = res.head; tmp != null; tmp = tmp.next)
         tmp.coeff *= num;

      return res;
   }
commented: Good work! +6

Solved most of issues, going to recondense single issues alot easier to rea
d

commented: More good work! +0

hey Bradoz, can u post the full solution including multiplication? thank you!!!!

if any one want the full polynomial addition,multiplication,sub code than contact me

Let me just add the usual health warning to the previous post. anand.khatik is a first-time poster; we have no information, good or bad, about his skills or credibility. Nobody has checked the email address he gives. Anyone copying someone else's code and submitting it as their own homework deserves the automatic fail they will probably get.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.