java service for calculator based on operator

• Can anybody know how to create java service, which will add, multiply, subtract, or divide two input numbers based on the operation value entered in input

1 Like

Hi Gireesh,

why not using the Built-In Services from pub.math-Folder in WmPublic package?

Here is an outline for the java service:

public float calc (int num1, int num2, char operator) throws Exception
{
case on operator:
‘+’: return num1+num2;
‘-’: return num1-num2;
'': return num1num2;
‘/’: return num1/num2;
}

Remember to add some checks to avoid division by zero (will cause an ArithmeticException) and that you received an expected operator or not.
Regards,
Holger

1 Like

Hi Holger,

I created calculator using WmPublic packages but my requirement is to create java service for calculator. In java service code parsing the operator(string taken as input) is not possible to parse as a character.

Calculator Service Using WmPublic Packages
calflow

Regards,
Gireesh Kumar G

1 Like

Hi Gireesh,

Try out below code in webMethods.

IDataCursor pipelineCursor = pipeline.getCursor();
int num1 = IDataUtil.getInt(“pipelineCursor”, “num1”);
int num2 = IDataUtil.getInt(“pipelineCursor”, “num2”);
String operator = IDataUtil.getString(“pipelineCursor”, “operator”);
pipelineCursor.destroy();

int result = 0;

switch(operator){

case “+” :
result = num1 + num2;
break;

case “-” :
result = num1 - num2;
break;

case “*” :
result = num1 * num2;
break;

case “/” :
result = num1 / num2;
break;

}

IDataCursor pipelineCursor2 = pipeline.getCursor();
IDataUtil.put(“pipelineCursor2”, “result”, result);
pipelineCursor2.destroy();

Please note that above code is for operating on int values.

Regards,
Jacob

2 Likes

Hi Gireesh,

We should always make use of provided built-in services like pub.math*** services as mentioned by @Holger_von_Thomsen and try to avoid writing our own java services.

Regarding parsing and transformation, you can again use built-in services from pub.string to handle whatever way you want to take care of.

If you insist on going with Java service only, then solutions are provided above in a good manner. you can enhance it as per your need like for debugging/error handling etc in case of specific operations like division.

Regards,
Firoz N

Got it by this way, Thanks Jacob.

Regards,
Gireesh Kumar G

Hi Jacob,

I would prefer to have the result as float or double here as the result of the division might not be an int number, but something with a fraction part, which can not be presented when using the result as int.
Or you should add some rounding or truncating after the division to make sure that result is an integer number.

Regards,
Holger

Hi Holger,

Rightly said !! That’s the reason i gave a disclaimer of using “int” which hold only decimal value instead of fraction.

As per my experience, big decimal is the best type for all math operations. :slight_smile:

Regards,
Jacob