Skip to content

Instantly share code, notes, and snippets.

@FrenchTechLead
Last active March 25, 2021 20:54
Show Gist options
  • Save FrenchTechLead/cf056c419f92c158b5b0e6e4fed3be0d to your computer and use it in GitHub Desktop.
Save FrenchTechLead/cf056c419f92c158b5b0e6e4fed3be0d to your computer and use it in GitHub Desktop.
Calculator V2
package meshredded;
import java.util.ArrayList;
import java.util.List;
import java.util.function.IntBinaryOperator;
class Calculator {
public static void main(String[] args) {
List<String> entries = new ArrayList<>();
entries.add("3 + 5");
entries.add("4 - 1");
entries.add("6 / 2");
entries.add("3 * 2");
entries.forEach(entry -> {
String[] splited = entry.split("\\+|\\-|\\/|\\*");
int left = new Integer(splited[0].trim());
int right = new Integer(splited[1].trim());
String symbol = entry.replaceAll("[0-9]|\\s", "");
int result = 0;
for (Operation op : Operation.values()) {
if (op.getSymbol().equals(symbol)) {
result = op.applyAsInt(left, right);
System.out.println(entry + " = " + result);
}
}
});
}
}
enum Operation implements IntBinaryOperator {
PLUS ("+", (l, r) -> l + r),
MINUS ("-", (l, r) -> l - r),
MULTIPLY ("*", (l, r) -> l * r),
DIVIDE ("/", (l, r) -> l / r);
private final String symbol;
private final IntBinaryOperator binaryOperator;
private Operation(final String symbol, final IntBinaryOperator binaryOperator) {
this.symbol = symbol;
this.binaryOperator = binaryOperator;
}
public String getSymbol() {
return symbol;
}
@Override
public int applyAsInt(int left, int right) {
return binaryOperator.applyAsInt(left, right);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment