leander
leander

Reputation: 33

Reading Polynomials from Input File (in Java)

I need to read a polynomial from a file. The problem I am facing is if the coefficients were more than one digit or if it had a negative sign, I don't know how to make the program recognize multiple digits are a single integer. That is going to really complicate my code when doing it manually since I need to make the program "aware" of its surrounding like when to start and stop. So, are there any in-built libraries that can be used to parse this? (While I was researching, I found Pattern and Matcher classes but not really sure if it can be used in this context).

For example, I know how to code for this 2x^2 + 4x + 8 but not for something like -22x^2 - 652x + 898.

Any help is appreciated.

Upvotes: 0

Views: 252

Answers (1)

T. Marquard
T. Marquard

Reputation: 26

I think you are on the right trail using Pattern and Matcher Class. I found this post: Splitting a string using Regex in Java

I am not completely sure what you are looking to do with this, or what the file looks like exactly, but pivoting off the above post you could do something like:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Polynomial
{
    public static void main (String[] args)
    {
        final String poly = "-2123x^-232-22x^2-652x+898";
        // Does not handle a missing + or - on the first term
        Pattern p = Pattern.compile("([-+]\\d+)x?[\\^]?([-]?\\d+)?");
        Matcher m = p.matcher(poly);
        while (m.find())
        {
            System.out.println("Entire match:" + m.group(0));
            // Showing option of casting to Integer
            System.out.println("Coefficient:" + Integer.parseInt(m.group(1)));
            // Possibly null since the last few parts don't have exponent or x
            if (null != m.group(2))
            {
                System.out.println("Exponent:" + m.group(2));
            }

        }
        
    }
}

Upvotes: 1

Related Questions