Reputation: 11
I am writing a program in Java that is going to be using polynomials. I need to be able to express polynomials based on something the user enters in.
For example the user might enter the following string.
"2, -7, 8, 0, -1
"
The polynomials for this here would be 2 - 7 x + 8 x^2 - x^4
But here's the catch. I cannot split the each number in the string into seperate ints using parse, this would be too easy! Because the String could have any number of numbers in it, this example has 5 numbers another might have 6, or less than that.
Any ideas as to how I could express a polynomial within Java?
Upvotes: 1
Views: 3893
Reputation: 77474
You can split the string using String.split()
without knowing the number of components. It will allocate the appropriate number of components for you.
Then convert it into an array of type int[]
which represents your polynomial...
Nothing particularly difficult here, everything is straightforward.
Upvotes: 1
Reputation: 680
If you can't use String.split()
and Integer.parseInt()
then:
Polynomial
class which takes a String
argument in its constructorand (
getNumber
method which uses indexOf
and substring
to return a String partgetCount
method which counts the commas in the stringor
Iterator
implementation)
Upvotes: 1
Reputation: 1915
String[] split = values.split(",\\s*");
This regex will also take care of additional spaces.
Upvotes: 2
Reputation: 500663
Any ideas as to how I could express a polynomial within java?
In my view the easiest is to have an array of int
(or float
/double
) coefficients. The number of elements in the array would depend in the degree of the polynomial.
I'd wrap this in a class and use String.split()
with Integer.valueOf()
(or Double.valueOf()
/Float.valueOf()
) to construct it from String
.
Upvotes: 1
Reputation: 4543
You should use String.split() and run it through a loop of Integer.valueOf() calls.
Upvotes: 1