Skip to content

Instantly share code, notes, and snippets.

@joshiraez
Created June 9, 2019 13:21
Show Gist options
  • Save joshiraez/3b697e43968a10b613ac4671b16bffd2 to your computer and use it in GitHub Desktop.
Save joshiraez/3b697e43968a10b613ac4671b16bffd2 to your computer and use it in GitHub Desktop.
Calculator done with enums for the operation
public class EnumCalculator {
//Notice how concise the code has become in the logic
public int calculate(char op, int a, int b) {
return OperationEnum.of(op).operate(a,b);
}
}
import java.util.HashMap;
import java.util.Map;
import java.util.function.BinaryOperator;
public enum OperationEnum {
OP_PLUS ((a,b) -> a+b),
OP_MINUS ((a,b) -> a-b),
OP_TIMES ((a,b) -> a*b),
OP_DIVISION ((a,b) -> a/b);
private static Map<Character, OperationEnum> operations =
new HashMap<Character, OperationEnum>() {{
put('+', OP_PLUS);
put('-', OP_MINUS);
put('x', OP_TIMES);
put('/', OP_DIVISION);
}};
private BinaryOperator<Integer> operation;
OperationEnum(BinaryOperator<Integer> operation) {
this.operation = operation;
}
public static OperationEnum of(char op) {
if(!operations.containsKey(op)) throw new IllegalArgumentException();
return operations.get(op);
}
public int operate(int a, int b) {
return operation.apply(a,b);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment