Skip to content

Instantly share code, notes, and snippets.

@kg6zvp
Last active April 19, 2018 19:35
Show Gist options
  • Save kg6zvp/5a80108b1284cfd9455cf64d4ef19d39 to your computer and use it in GitHub Desktop.
Save kg6zvp/5a80108b1284cfd9455cf64d4ef19d39 to your computer and use it in GitHub Desktop.
Calculator Class for Tutorial 12 - Business Logic and @Inject
package com.airhacks;
import java.util.Arrays;
import java.util.stream.Collectors;
import javax.enterprise.context.RequestScoped;
/**
*
* @author smccollum
*/
@RequestScoped
public class Calculator {
public int processRequest(String expression){
if(expression.contains("*")){
Integer[] ops = parseOperation(expression, "\\*");
return multiply(ops[0], ops[1]);
}else if(expression.contains("+")){
Integer[] ops = parseOperation(expression, "\\+");
return add(ops[0], ops[1]);
}else if(expression.contains("-")){
Integer[] ops = parseOperation(expression, "-");
return subtract(ops[0], ops[1]);
}else if(expression.contains("/")){
Integer[] ops = parseOperation(expression, "/");
return divide(ops[0], ops[1]);
}
return 0;
}
private Integer[] parseOperation(String exp, String operation){
return Arrays.stream(exp.split(operation))
.map(Integer::valueOf)
.collect(Collectors.toList())
.toArray(new Integer[]{});
}
private int add(int a, int b){
return a + b;
}
private int subtract(int a, int b){
return a - b;
}
private int multiply(int a, int b){
return a * b;
}
private int divide(int a, int b){
return a / b;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment