Last active
March 25, 2021 20:54
-
-
Save FrenchTechLead/cf056c419f92c158b5b0e6e4fed3be0d to your computer and use it in GitHub Desktop.
Calculator V2
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
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