SlideShare a Scribd company logo
1 of 7
Download to read offline
Main issues with the following code:Im not sure if its reading the file correctly because its
adding all terms together. In other words the the first line of terms is adding the second line of
terms but thats not my intention. Each line of term should have their own polynomial expression
as shown below
Basic specifications :
The code should add the polynomial numbers using a linked list. Java . Keep in mind the
polynomials will be gotten from a file.
Things to keep in mind the list should be in decending order and traverse the list after
all coefficient/exponent pair Term nodes from one input line have been
inserted.
Here are the specifications
//The Polynomial class would likely have a single private data member (reference to
class Term) called head.
//The Term class would likely have three private data
members (coefficient and exponent of type int) and next of type reference to
Term.
//The latter class would also have the following public methods:
constructor(s), gets and sets for each data member, and perhaps a formatting
method with the special output requirements.
An example of input is 7 1 2 4 6 2 -3 2 -1 -1 3
Negative negative
pair signals the termination
***NO doubly linked list , it should be a single linked list **
Input file contains the following :
7 1 2 4 6 2 -3 2 -1 -1 3 ----> 2x^4 - 3x^2 +6x^2 + 7x
5 1 2 3 6 0 -3 2 -1 -1 3 ----> 2*X^3 + (-3)*X^2 + 5*X + 6 // thats the ouput for one line of the
the file , each line of the file should have one polynomial output
Code
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Polynomial {
private Term head;
// Constructor for creating an empty polynomial object
public Polynomial() {
head = null;
}
// Method for adding a term to the polynomial, this is inside the polynomial term
public void addTerm(int coefficient, int exponent) {
// Create a new term object
Term newTerm = new Term(coefficient, exponent);
// If the polynomial is empty, set the new term as the head
if (head == null) {
head = newTerm;
} else {
// Traverse the polynomial until we find the correct position for the new term
Term current = head;
Term previous = null;
while (current != null && current.getExponent() > exponent) {
previous = current;
current = current.getNext();
}
// If a term with the same exponent already exists, add the coefficients
if (current != null && current.getExponent() == exponent) {
current.setCoefficient(current.getCoefficient() + coefficient);
} else {
// Otherwise, insert the new term into the polynomial
if (previous == null) {
head = newTerm;
} else {
previous.setNext(newTerm);
}
newTerm.setNext(current);
}
}
// Method for formatting the polynomial as a string
public String toString() {
StringBuilder sb = new StringBuilder();
if (head != null) {
sb.append(head.toString());
Term current = head.getNext();
while (current != null) {
if (current.getCoefficient() > 0) {
sb.append(" + ");
} else {
sb.append(" - ");
}
sb.append(current.toString());
current = current.getNext();
}
}
return sb.toString();
}
}
public class Term {
private int coefficient;
private int exponent;
private Term next;
// Constructor for creating a new term object
public Term(int coefficient, int exponent) {
this.coefficient = coefficient;
this.exponent = exponent;
next = null;
}
// Getter and setter methods for the coefficient and exponent
public int getCoefficient() {
return coefficient;
}
public void setCoefficient(int coefficient) {
this.coefficient = coefficient;
}
public int getExponent() {
return exponent;
}
public void setExponent(int exponent) {
this.exponent = exponent;
}
// Getter and setter methods for the next term in the polynomial
public Term getNext() {
return next;
}
public void setNext(Term next) {
this.next = next;
}
// Method for formatting the term as a string
public String toString() {
if (exponent == 0) {
return Integer.toString(coefficient);
} else if (exponent == 1) {
if (coefficient == 1) {
return "x";
} else if (coefficient == -1) {
return "-x";
} else {
return coefficient + "x";
}
} else {
if (coefficient == 1) {
return "x^" + exponent;
} else if (coefficient == -1) {
return "-x^" + exponent;
} else {
return coefficient + "x^" + exponent;
}
}
}
}
import java.io.File;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) {
Polynomial p = new Polynomial();
try {
Scanner input = new Scanner(new File("polynomial.txt"));
while (input.hasNextLine()) {
String line = input.nextLine();
String[] tokens = line.split(" ");
int coefficient = Integer.parseInt(tokens[0]);
int exponent = Integer.parseInt(tokens[1]);
p.addTerm(coefficient, exponent);
}
input.close();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
System.exit(1);
}
System.out.println("Polynomial: " + p);
}
}

More Related Content

Similar to Main issues with the following code-Im not sure if its reading the fil.pdf

So here is the code from the previous assignment that we need to ext.pdf
So here is the code from the previous assignment that we need to ext.pdfSo here is the code from the previous assignment that we need to ext.pdf
So here is the code from the previous assignment that we need to ext.pdf
leolight2
 
Consider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxConsider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docx
maxinesmith73660
 
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdfNeed done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
info114
 
This assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfThis assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdf
EricvtJFraserr
 
Please need help on following program using c++ language. Please inc.pdf
Please need help on following program using c++ language. Please inc.pdfPlease need help on following program using c++ language. Please inc.pdf
Please need help on following program using c++ language. Please inc.pdf
nitinarora01
 
We will be making 4 classes Main - for testing the code Hi.pdf
 We will be making 4 classes Main - for testing the code Hi.pdf We will be making 4 classes Main - for testing the code Hi.pdf
We will be making 4 classes Main - for testing the code Hi.pdf
anithareadymade
 
In this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdfIn this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdf
contact41
 
Question 1 has already been posted to Chegg and I am waiting for the.pdf
Question 1 has already been posted to Chegg and I am waiting for the.pdfQuestion 1 has already been posted to Chegg and I am waiting for the.pdf
Question 1 has already been posted to Chegg and I am waiting for the.pdf
anjandavid
 
Assignment is Page 349-350 #4 and #5 Use the Linked Lis.pdf
Assignment is Page 349-350 #4 and #5 Use the Linked Lis.pdfAssignment is Page 349-350 #4 and #5 Use the Linked Lis.pdf
Assignment is Page 349-350 #4 and #5 Use the Linked Lis.pdf
formicreation
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
aromanets
 
Hey, I need some help coding this C++ assignment.ObjectivesThis.pdf
Hey, I need some help coding this C++ assignment.ObjectivesThis.pdfHey, I need some help coding this C++ assignment.ObjectivesThis.pdf
Hey, I need some help coding this C++ assignment.ObjectivesThis.pdf
rishabjain5053
 
Task #1 Correcting Logic Errors in FormulasCopy and compile the so.pdf
Task #1 Correcting Logic Errors in FormulasCopy and compile the so.pdfTask #1 Correcting Logic Errors in FormulasCopy and compile the so.pdf
Task #1 Correcting Logic Errors in FormulasCopy and compile the so.pdf
info706022
 

Similar to Main issues with the following code-Im not sure if its reading the fil.pdf (20)

So here is the code from the previous assignment that we need to ext.pdf
So here is the code from the previous assignment that we need to ext.pdfSo here is the code from the previous assignment that we need to ext.pdf
So here is the code from the previous assignment that we need to ext.pdf
 
C++ Please write the whole code that is needed for this assignment- wr.docx
C++ Please write the whole code that is needed for this assignment- wr.docxC++ Please write the whole code that is needed for this assignment- wr.docx
C++ Please write the whole code that is needed for this assignment- wr.docx
 
create-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdfcreate-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdf
 
ForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptx
 
Java execise
Java execiseJava execise
Java execise
 
Consider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxConsider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docx
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput
 
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdfNeed done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
 
Python 3000
Python 3000Python 3000
Python 3000
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
 
This assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfThis assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdf
 
Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts
 
Please need help on following program using c++ language. Please inc.pdf
Please need help on following program using c++ language. Please inc.pdfPlease need help on following program using c++ language. Please inc.pdf
Please need help on following program using c++ language. Please inc.pdf
 
We will be making 4 classes Main - for testing the code Hi.pdf
 We will be making 4 classes Main - for testing the code Hi.pdf We will be making 4 classes Main - for testing the code Hi.pdf
We will be making 4 classes Main - for testing the code Hi.pdf
 
In this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdfIn this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdf
 
Question 1 has already been posted to Chegg and I am waiting for the.pdf
Question 1 has already been posted to Chegg and I am waiting for the.pdfQuestion 1 has already been posted to Chegg and I am waiting for the.pdf
Question 1 has already been posted to Chegg and I am waiting for the.pdf
 
Assignment is Page 349-350 #4 and #5 Use the Linked Lis.pdf
Assignment is Page 349-350 #4 and #5 Use the Linked Lis.pdfAssignment is Page 349-350 #4 and #5 Use the Linked Lis.pdf
Assignment is Page 349-350 #4 and #5 Use the Linked Lis.pdf
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
 
Hey, I need some help coding this C++ assignment.ObjectivesThis.pdf
Hey, I need some help coding this C++ assignment.ObjectivesThis.pdfHey, I need some help coding this C++ assignment.ObjectivesThis.pdf
Hey, I need some help coding this C++ assignment.ObjectivesThis.pdf
 
Task #1 Correcting Logic Errors in FormulasCopy and compile the so.pdf
Task #1 Correcting Logic Errors in FormulasCopy and compile the so.pdfTask #1 Correcting Logic Errors in FormulasCopy and compile the so.pdf
Task #1 Correcting Logic Errors in FormulasCopy and compile the so.pdf
 

More from aonesalem

More from aonesalem (20)

Many of the regulations you have read about this week were developed f.pdf
Many of the regulations you have read about this week were developed f.pdfMany of the regulations you have read about this week were developed f.pdf
Many of the regulations you have read about this week were developed f.pdf
 
Many organizations are utilizing social media as part of their promoti.pdf
Many organizations are utilizing social media as part of their promoti.pdfMany organizations are utilizing social media as part of their promoti.pdf
Many organizations are utilizing social media as part of their promoti.pdf
 
Many of the genes in Escherichia coil O157-H7 come from bacteriophage.pdf
Many of the genes in Escherichia coil O157-H7 come from bacteriophage.pdfMany of the genes in Escherichia coil O157-H7 come from bacteriophage.pdf
Many of the genes in Escherichia coil O157-H7 come from bacteriophage.pdf
 
Many innovations in biotechnology are derivatives of a naturally occur.pdf
Many innovations in biotechnology are derivatives of a naturally occur.pdfMany innovations in biotechnology are derivatives of a naturally occur.pdf
Many innovations in biotechnology are derivatives of a naturally occur.pdf
 
Many Canadians workers and politicians are worried about the impact of.pdf
Many Canadians workers and politicians are worried about the impact of.pdfMany Canadians workers and politicians are worried about the impact of.pdf
Many Canadians workers and politicians are worried about the impact of.pdf
 
Manegement is the coordination of actlvities within an orgarication th.pdf
Manegement is the coordination of actlvities within an orgarication th.pdfManegement is the coordination of actlvities within an orgarication th.pdf
Manegement is the coordination of actlvities within an orgarication th.pdf
 
Manny Lawson Corp- had the following current account values- What effe.pdf
Manny Lawson Corp- had the following current account values- What effe.pdfManny Lawson Corp- had the following current account values- What effe.pdf
Manny Lawson Corp- had the following current account values- What effe.pdf
 
Many American suffer from some form of Diabetes- Pick a type or cause.pdf
Many American suffer from some form of Diabetes- Pick a type or cause.pdfMany American suffer from some form of Diabetes- Pick a type or cause.pdf
Many American suffer from some form of Diabetes- Pick a type or cause.pdf
 
MANE Competence Statement- A competent nurse develops insight through.pdf
MANE Competence Statement- A competent nurse develops insight through.pdfMANE Competence Statement- A competent nurse develops insight through.pdf
MANE Competence Statement- A competent nurse develops insight through.pdf
 
Managers engage in planning- organizing- directing and controlling in.pdf
Managers engage in planning- organizing- directing and controlling in.pdfManagers engage in planning- organizing- directing and controlling in.pdf
Managers engage in planning- organizing- directing and controlling in.pdf
 
Management is the coordination of activies within an organization that.pdf
Management is the coordination of activies within an organization that.pdfManagement is the coordination of activies within an organization that.pdf
Management is the coordination of activies within an organization that.pdf
 
Management- For a small IT company (providing software development and.pdf
Management- For a small IT company (providing software development and.pdfManagement- For a small IT company (providing software development and.pdf
Management- For a small IT company (providing software development and.pdf
 
Management's Discussion and Analysis can be substituted for the notes.pdf
Management's Discussion and Analysis can be substituted for the notes.pdfManagement's Discussion and Analysis can be substituted for the notes.pdf
Management's Discussion and Analysis can be substituted for the notes.pdf
 
Management is often faced with the alternative of continuing to make a.pdf
Management is often faced with the alternative of continuing to make a.pdfManagement is often faced with the alternative of continuing to make a.pdf
Management is often faced with the alternative of continuing to make a.pdf
 
Management fraud (fraudulent financial reporting) is not the expected.pdf
Management fraud (fraudulent financial reporting) is not the expected.pdfManagement fraud (fraudulent financial reporting) is not the expected.pdf
Management fraud (fraudulent financial reporting) is not the expected.pdf
 
Management fees are 3- at an investment bank- Alternative asset manage.pdf
Management fees are 3- at an investment bank- Alternative asset manage.pdfManagement fees are 3- at an investment bank- Alternative asset manage.pdf
Management fees are 3- at an investment bank- Alternative asset manage.pdf
 
Management accounting- Muitiple Choice is an extremely specialized sub.pdf
Management accounting- Muitiple Choice is an extremely specialized sub.pdfManagement accounting- Muitiple Choice is an extremely specialized sub.pdf
Management accounting- Muitiple Choice is an extremely specialized sub.pdf
 
MALDI-TOF MS is used to determine what aspect of the analyte(s)- Molec.pdf
MALDI-TOF MS is used to determine what aspect of the analyte(s)- Molec.pdfMALDI-TOF MS is used to determine what aspect of the analyte(s)- Molec.pdf
MALDI-TOF MS is used to determine what aspect of the analyte(s)- Molec.pdf
 
Makin the deeapbon of prease so the sepiopicte hormed eleatent Eintrom.pdf
Makin the deeapbon of prease so the sepiopicte hormed eleatent Eintrom.pdfMakin the deeapbon of prease so the sepiopicte hormed eleatent Eintrom.pdf
Makin the deeapbon of prease so the sepiopicte hormed eleatent Eintrom.pdf
 
make macros for each of the following procedures I combed through the.pdf
make macros for each of the following procedures I combed through the.pdfmake macros for each of the following procedures I combed through the.pdf
make macros for each of the following procedures I combed through the.pdf
 

Recently uploaded

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 

Main issues with the following code-Im not sure if its reading the fil.pdf

  • 1. Main issues with the following code:Im not sure if its reading the file correctly because its adding all terms together. In other words the the first line of terms is adding the second line of terms but thats not my intention. Each line of term should have their own polynomial expression as shown below Basic specifications : The code should add the polynomial numbers using a linked list. Java . Keep in mind the polynomials will be gotten from a file. Things to keep in mind the list should be in decending order and traverse the list after all coefficient/exponent pair Term nodes from one input line have been inserted. Here are the specifications //The Polynomial class would likely have a single private data member (reference to class Term) called head. //The Term class would likely have three private data members (coefficient and exponent of type int) and next of type reference to Term. //The latter class would also have the following public methods: constructor(s), gets and sets for each data member, and perhaps a formatting method with the special output requirements. An example of input is 7 1 2 4 6 2 -3 2 -1 -1 3 Negative negative pair signals the termination ***NO doubly linked list , it should be a single linked list ** Input file contains the following : 7 1 2 4 6 2 -3 2 -1 -1 3 ----> 2x^4 - 3x^2 +6x^2 + 7x 5 1 2 3 6 0 -3 2 -1 -1 3 ----> 2*X^3 + (-3)*X^2 + 5*X + 6 // thats the ouput for one line of the the file , each line of the file should have one polynomial output Code import java.io.File; import java.io.FileNotFoundException;
  • 2. import java.util.Scanner; public class Polynomial { private Term head; // Constructor for creating an empty polynomial object public Polynomial() { head = null; } // Method for adding a term to the polynomial, this is inside the polynomial term public void addTerm(int coefficient, int exponent) { // Create a new term object Term newTerm = new Term(coefficient, exponent); // If the polynomial is empty, set the new term as the head if (head == null) { head = newTerm; } else { // Traverse the polynomial until we find the correct position for the new term Term current = head; Term previous = null; while (current != null && current.getExponent() > exponent) { previous = current; current = current.getNext(); } // If a term with the same exponent already exists, add the coefficients
  • 3. if (current != null && current.getExponent() == exponent) { current.setCoefficient(current.getCoefficient() + coefficient); } else { // Otherwise, insert the new term into the polynomial if (previous == null) { head = newTerm; } else { previous.setNext(newTerm); } newTerm.setNext(current); } } // Method for formatting the polynomial as a string public String toString() { StringBuilder sb = new StringBuilder(); if (head != null) { sb.append(head.toString()); Term current = head.getNext(); while (current != null) { if (current.getCoefficient() > 0) { sb.append(" + "); } else { sb.append(" - ");
  • 4. } sb.append(current.toString()); current = current.getNext(); } } return sb.toString(); } } public class Term { private int coefficient; private int exponent; private Term next; // Constructor for creating a new term object public Term(int coefficient, int exponent) { this.coefficient = coefficient; this.exponent = exponent; next = null; } // Getter and setter methods for the coefficient and exponent public int getCoefficient() { return coefficient; } public void setCoefficient(int coefficient) {
  • 5. this.coefficient = coefficient; } public int getExponent() { return exponent; } public void setExponent(int exponent) { this.exponent = exponent; } // Getter and setter methods for the next term in the polynomial public Term getNext() { return next; } public void setNext(Term next) { this.next = next; } // Method for formatting the term as a string public String toString() { if (exponent == 0) { return Integer.toString(coefficient); } else if (exponent == 1) { if (coefficient == 1) { return "x"; } else if (coefficient == -1) {
  • 6. return "-x"; } else { return coefficient + "x"; } } else { if (coefficient == 1) { return "x^" + exponent; } else if (coefficient == -1) { return "-x^" + exponent; } else { return coefficient + "x^" + exponent; } } } } import java.io.File; import java.io.FileNotFoundException; public class Main { public static void main(String[] args) { Polynomial p = new Polynomial(); try { Scanner input = new Scanner(new File("polynomial.txt")); while (input.hasNextLine()) {
  • 7. String line = input.nextLine(); String[] tokens = line.split(" "); int coefficient = Integer.parseInt(tokens[0]); int exponent = Integer.parseInt(tokens[1]); p.addTerm(coefficient, exponent); } input.close(); } catch (FileNotFoundException e) { System.out.println("File not found: " + e.getMessage()); System.exit(1); } System.out.println("Polynomial: " + p); } }