Created
June 9, 2019 13:21
-
-
Save joshiraez/3b697e43968a10b613ac4671b16bffd2 to your computer and use it in GitHub Desktop.
Calculator done with enums for the operation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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