user1132528
user1132528

Reputation: 11

Convert from a String to a polynomial

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

Answers (5)

Has QUIT--Anony-Mousse
Has QUIT--Anony-Mousse

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

David
David

Reputation: 680

If you can't use String.split() and Integer.parseInt() then:

  • make a Polynomial class which takes a String argument in its constructor

and (

  • a getNumber method which uses indexOf and substring to return a String part
  • a getCount method which counts the commas in the string

or

  • implement java.lang.Iterable interface, and use the techniques described above in the Iterator implementation

)

Upvotes: 1

Rogel Garcia
Rogel Garcia

Reputation: 1915

String[] split = values.split(",\\s*");

This regex will also take care of additional spaces.

Upvotes: 2

NPE
NPE

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

Rostislav Matl
Rostislav Matl

Reputation: 4543

You should use String.split() and run it through a loop of Integer.valueOf() calls.

Upvotes: 1

Related Questions