1. Member
Join Date
Oct 2012
Posts
10
Rep Power
0

## Writing 'polynomial' class

Hey all, I'm writing a polynomial class that will have methods to output, evaluate, add, subtract, and multiply polynomials. I'm going to use the driver class to read a text file formatted like this:

Java Code:
```3
First 6 3 4 1 2 0
Second 10 12 18 6 -4 2 1 1
Third 4 1 -20 0```
The first line will simply indicate the number of lines, while each line after indicates the name of the polynomial, and then switch between integers of the coefficients and then the degrees of the term exponent.

6X^3 + 0X^2 + 4X^1 + 2X^0 <--first line

The 'polynomial' class is the part that I am stumped on, if I read the lines with scanner in the driver and pass the subsequent lines as Strings to the polynomial class, how can I tokenize (or use whatever method) the 'ints' in the Sting line and store them to a single array where the index is the degree of the polynomial and the int stored is the coefficient? It only has to work up to a degree of 20. (X^20)

Any help is greatly appreciated. If I can get this part of the polynomial class working, I can figure out everything else out.

2. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,712
Rep Power
14

## Re: Writing 'polynomial' class

I'd represent a polynomial as some sort of Map whose keys and values are both Integer (the power and coefficient respectively). The only "tokenising" needed is that provided by the String split() method.

Supposing that the index always lies >=0 and <=20 then an int array (of length 21) could play the role of the map. Just make sure that "unused" terms have a coefficient of zero. Again the only parsing or tokenising you have to do is that provided by split(). I suggest you write some code to test, experiment and get familiar with both split() and the parse() method of Integer. This latter is what enables you to calculate the int value associated with the strings obtained from the input.

---

Personally, as I said, if I wanted a map I'd go for a Map: because that's the most straight forward thing to do. Certainly there might be efficiency to be had by using int arrays to implement my own map or sparse array, but I'd put off such complications until the polynomial behaviour was done, tested and found to be correct.

Notice that the restriction on the range of the index (which has a whiff about it, of being an ad hoc "requirement" facilitating the use of arrays...) means that the product of two polynomials won't always be defined.