Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp

Callum Owen

Greenhorn
+ Follow
since May 01, 2019
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by Callum Owen

I need to call the parse expression method in my JAX-RS using the @post method that accepts a string from a client.

below is the code i have the first bit of code only dose basic interger maths and the second bit of code does the parse expression but doesn't use JAX-RS

first code

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

public class ExpressionParser {

public static final Pattern SPLIT_REGEX = Pattern.compile("(?[-]?\\d+)([-+/*=])?)");

public long parseExpression(String expression) {
long left = 0;
char operator = '+';
Matcher m = SPLIT_REGEX.matcher(expression);
while (m.find()) {
String operand = "";
try {
operand = m.group(1);
} catch (IndexOutOfBoundsException e) {
operand = "0";
}
left = calculate(left, operator, Long.valueOf(operand));

String oper = m.group(2);
if (oper != null)
operator = oper.charAt(0);

}
return left;
}

private long calculate(long left, char operator, long right) {
switch (operator) {
case '+':
return left + right;
case '-':
return left - right;
case '*':
return left * right;
case '/':
return left / right;
case '=':
return left;
default:
return 0L;
}
}
}
second code

@Path("calculate")
public class Calculator {

   private final Long value;

   public Calculator() {
       value = 0L;
   }

   public Calculator(Long initialValue) {
       this.value = initialValue;
   }

   @GET
   public Long getValue() {
       return value;
   }

   @Path("add/{value1}/{value2}")
   @GET
   @Produces(MediaType.APPLICATION_JSON)
   public Long add(@PathParam("value1") Long value, @PathParam("value2") Long value2) {
       return value + value2;
   }
   @Path("subtract/{value1}/{value2}")
   @GET
   @Produces(MediaType.APPLICATION_JSON)
   public Long subtract(@PathParam("value1") Long value, @PathParam("value2") Long value2) {
       return value - value2;
   }
   @Path("multipli/{value1}/{value2}")
   @GET
   @Produces(MediaType.APPLICATION_JSON)
   public Long multipli(@PathParam("value1") Long value, @PathParam("value2") Long value2) {
       return value * value2;
   }
   @Path("divide/{value1}/{value2}")
   @GET
   @Produces(MediaType.APPLICATION_JSON)
   public Long divide(@PathParam("value1") Long value, @PathParam("value2") Long value2) {
       return value / value2;
   }
}
3 weeks ago