• 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
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.
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
Gireesh Kumar G
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”);
int result = 0;
case “+” :
result = num1 + num2;
case “-” :
result = num1 - num2;
case “*” :
result = num1 * num2;
case “/” :
result = num1 / num2;
IDataCursor pipelineCursor2 = pipeline.getCursor();
IDataUtil.put(“pipelineCursor2”, “result”, result);
Please note that above code is for operating on int values.
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.
Got it by this way, Thanks Jacob.
Gireesh Kumar G
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.
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.