Java quadratic parser PDF Print E-mail
Written by Charles   
Tuesday, 08 December 2009 14:39

It's possible to parse expressions in Java using regex for simple cases, such as the below which will accept only integer coefficients currently, although for more serious work, an expression parser should be used. Below is an example of parsing a quadratic expression. The code is HERE

import java.util.regex.*;


public class Quad {
    /**
     * Test the quadratic parser by solving
     * an equation
     *
     * @param args An equation of the form 'ax^2+bx+c'
     */
    public static void main(String[] args) {
        int[] coeff = Quad.parseQuadratic(args[0]);
        System.out.println(java.util.Arrays.toString(coeff));

        int a = coeff[0];
        int b = coeff[1];
        int c = coeff[2];
        double root1 = (-b + Math.sqrt((b * b) - (4 * a * c))) / (2 * a);
        double root2 = (-b - Math.sqrt((b * b) - (4 * a * c))) / (2 * a);
        System.out.printf("Roots are %f and %f\n", root1, root2);
    }

    /**
     *
     * @param s An equation of the form 'ax^2+bx+c'
     *
     * @return An array of coefficients/constant
     */
    public static int[] parseQuadratic(String s) {
        // Clean expression of whitespace
        s = s.replaceAll("\\s", "");
        int[] result = new int[3];
        Pattern p = Pattern.compile("(\\d*)x\\^2(?:([+\\-]\\d*)x)?([+\\-]\\d*)?");
        Matcher m = p.matcher(s);

        if (m.matches()) {
            for (int i = 1; i <= m.groupCount(); i++) {
                String x = m.group(i);

                if (x == null) {
                    x = "0";
                }

                if (x.startsWith("+")) {
                    x = x.substring(1);
                }

                if ("".equals(x) || "-".equals(x)) {
                    x += "1";
                }

                result[i - 1] = Integer.valueOf(x);
            }
        } else {
            throw new IllegalArgumentException(String.format(
                        "Invalid quadratic:  %s", s));
        }

        return result;
    }
}
Comments
Search
Only registered users can write comments!

3.26 Copyright (C) 2008 Compojoom.com / Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved."

Last Updated ( Tuesday, 08 December 2009 14:50 )