0

i am developing an application in JAVA jdbc, in which i add new shapes and their formulas than calculate its area, question is something like this,

web page should show a list of shapes (circle, square, rectangle, elipse) and statistics for each shape.

When you click on a shape, you are asked to enter dimensions.

For circle, only diameter is required

For elipse, height and width is required

... etc ...

After entering the dimensions, the area of the shape will be calculated, and the statistics will be updated.

It should be easy to add new types of shapes in the future.

i have developed almost everything, but only problem is how to dynamically calculate formulas, when a shape is entered its formula saved in database, now when i ask for calculate formula, so i gave values from frontend and their formula arrive from dataabse so it calculate and show result, recently i hard code formulas in servlet like this

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Shapes shape = new Shapes();
        int id = Integer.parseInt(request.getParameter("id"));

        int count = Integer.parseInt(request.getParameter("count")); 
        double values = Double.parseDouble(request.getParameter("name0")); // here values of shapes came from form jsp (form)

        double area = 3.14159 * values * values; // i don't want to hardcode formulas
        shape.setShapeId(id);
        shape.setShapeCount(count);
        shape.setShapeArea(area);
        shapesDao.updateShapeArea(shape);
}

**All i Want to formula values came from jsp (forms) and in servlet formula of that shape came from database by its id, than formula executed and return result **

i searched and figure out it is done by JEXL apache library, but i am not able to use this library kindly provide me help with code, i'll be greatfull to you.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String formula = null;
        Shapes shape = new Shapes();
        int id = Integer.parseInt(request.getParameter("id"));

        int count = Integer.parseInt(request.getParameter("count"));
        double values = Double.parseDouble(request.getParameter("name0"));

        Map m  = request.getParameterMap();
        Set s = m.entrySet();
        Iterator it = s.iterator();

        while(it.hasNext()){

            Map.Entry<String,String[]> entry = (Map.Entry<String,String[]>)it.next();

            String key             = entry.getKey();
            String[] value         = entry.getValue();

            System.out.println("Key is "+key);

                if(value.length>1){    
                    for (int i = 0; i < value.length; i++) {
                        System.out.println("value is "+value[i].toString());
                    }
                }else
                    System.out.println("Value is "+value[0].toString());


        }

    List<Shapes> allShapes = shapesDao.getAllShapes();
        for (Shapes shapeobj : allShapes)
        {
            if(shapeobj.getShapeId() == id)
            {
                formula = shapeobj.getShapeFormula();
            }
        }

here i have values in map and formula is in formula varialbe
now how to store values in this polynomial answered bt Bohemian in the way its formula is ? 






        System.out.println("Formula is "+formula);
        shape.setShapeId(id);
        shape.setShapeCount(count);
        shape.setShapeArea(area);
        shapesDao.updateShapeArea(shape);

        List<Shapes> shapes = shapesDao.getAllShapes();
        System.out.println("size in server "+shapes.size());
        request.setAttribute("data", shapes);
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }

formulas may be different for different shapes

  • circle (3.14*radius*radius)
  • elippse(3.14*aaxis*baxis)
  • rectangle(width*length)
  • square(a*a)

and so on

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Ahmad
  • 1,462
  • 5
  • 17
  • 40
  • FYI: java has [`Math.PI`](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#PI) constant with more precision than your hard-coded one in the quesiton. Might as well use the constant for both better readability and precision. – Asaph Apr 11 '16 at 05:40
  • thanks but it is not what i ask.. – Ahmad Apr 11 '16 at 05:57
  • 1
    That's why I left it as a comment and not an answer. :) – Asaph Apr 11 '16 at 06:09

3 Answers3

1

All areas a 2nd order polynomial expressions, which have only 3 coefficients:

Given (up to) 2 dimensions, x and y (y is zero for single dimensioned shapes):

area = ax2 + bxy + cy2

so all you need to do is store these 3 numbers.

Here are some sets:

shape    |  a  |  b  |  c  
circle   | pi  |  0  |  0
square   |  1  |  0  |  0
triangle |  0  |  .5 |  0
ellipse  |  0  | pi  |  0

etc

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • how to store these values in this polynomial in generic format, because if i add new shapes i don't want to write code again in my server. i am very confused, kindly provide me a method as i mentioned in question, i want to make that function is generic for all previous shape and all new added shapes, kindly help me with code, i understand your answer but i am not able to code it..your code may made my day. – Ahmad Apr 11 '16 at 06:26
  • If you can't store 3 numbers, then this answer won't help you. – Bohemian Apr 11 '16 at 06:30
  • kindly take a look in question again i have add one thing, please answer it with code,,,plz plz – Ahmad Apr 11 '16 at 06:39
0

direct sense of "formula saved in database" lead to interpreters. There are many https://en.wikipedia.org/wiki/List_of_JVM_languages

I don't have contact with jexl but here is code: http://commons.apache.org/proper/commons-jexl/reference/examples.html What is hard to understand?

Personally I integrate groovy with (big) servlet project for such dynamic computation.

Java 8 (SDK, not JRE) has dynamic compiler built-in. How do you dynamically compile and load external java classes?

You can declare interface Shape in main code, implement few overrides in database.

EDIT: question is not clear, in one place say "formula in database" is the other negate this requirement.

EDIT2: here is interface for dynamic count of sizes, ie Circle has one "Radius" etc ...

interface Shape {
 String getSahpeName(); // "Circle"
 String[] getNamesOfSizes(); // { "Radius" }
 void setSize(String name, double val);
 double getSize(String name);

 double compute(); // Pi*r^2
}
Community
  • 1
  • 1
Jacek Cz
  • 1,872
  • 1
  • 15
  • 22
  • if you made my function generic, i.e is values of areas came from jsp and formula of that shape came from database, it automatically calculate formula, i want to make that function is generic for all previous shape and all new added shapes, kindly help me with code i am stuck in this question by last 1 week, your code may made my day... – Ahmad Apr 11 '16 at 06:30
  • kindly take a look in question again i have add one thing, please answer it with code,,,plz plz – Ahmad Apr 11 '16 at 06:39
  • Sorry @Ahmad, I don't understand what kind of help You want. – Jacek Cz Apr 11 '16 at 06:43
  • I don't understand You in word "generic", You use few times. In Java this word has other sense. – Jacek Cz Apr 11 '16 at 06:44
  • it means method is something like this, formulas of shape may be different so any formula i want to calculate i dont want to change my function, method is written in a way any formula came it calculate it... – Ahmad Apr 11 '16 at 06:46
0

i have done it with apache JEXL Library

here is the code

List<Shapes> allShapes = shapesDao.getAllShapes();
        for (Shapes shapeobj : allShapes)
        {
            if(shapeobj.getShapeId() == id)
            {
                formula = shapeobj.getShapeFormula();
            }
        }
        final JexlEngine jexl = new 

    JexlBuilder().cache(512).strict(true).silent(false).create();
            String jexlExp = formula;

            JexlExpression  e = jexl.createExpression(formula);
            JexlContext context = new MapContext();
            for(int i = 0; i<params; i++)
            {
                for(int j=0;j<completed.length;j++)
                {
                    System.out.println("-------------------------");
                    System.out.println(completed[j]);
                    System.out.println("-------------------------");
                    context.set(completed[j], request.getParameter(completed[j]));
                }
            }


            Object o = e.evaluate(context);
Ahmad
  • 1,462
  • 5
  • 17
  • 40