Skip to content

Instantly share code, notes, and snippets.

@thiagotn
Last active January 29, 2016 21:09
Show Gist options
  • Save thiagotn/8a9f6d5ea92b6f2d3606 to your computer and use it in GitHub Desktop.
Save thiagotn/8a9f6d5ea92b6f2d3606 to your computer and use it in GitHub Desktop.
Calculator Simples
import java.util.Arrays;
import java.util.List;
public class Calculator {
public static void main(String[] args) {
Calculator calculator = new Calculator();
//Double result = calculator.calcWithArray(Arrays.asList("5", "*", "4", "+", "2", "-", "9", "+", "7", "/", "2")); // 10
Double result = calculator.calcWithArray(Arrays.asList("1", "/", "0"));
System.out.println(result);
}
public Double calcWithArray(List<String> values) {
Double total = null;
if (values == null || values.isEmpty() || values.size() < 3) {
throw new IllegalArgumentException("Nothing to do!");
}
Double actualValue1 = null;
Operation actualOperation = null;
Double actualValue2 = null;
for (String value : values) {
if (isCharOperation(value)) {
actualOperation = Operation.fromCharactere(value);
} else {
if (actualValue1 == null) {
actualValue1 = Double.parseDouble(value);
} else if (actualValue2 == null) {
actualValue2 = Double.parseDouble(value);
}
}
// Se existem parametros para realizar um calculo, faremos
if (actualValue1 != null && actualValue2 != null && actualOperation != null) {
// Acrescentando ao resultado
total = 0.0D;
total += calc(actualValue1, actualValue2, actualOperation);
actualValue1 = null;
actualValue2 = null;
actualOperation = null;
} else if (total != null && actualOperation != null && actualValue1 != null) {
total = calc(total, actualValue1, actualOperation);
actualValue1 = null;
actualValue2 = null;
actualOperation = null;
}
}
return total;
}
Double calc(Double value1, Double value2, Operation operation) {
Double total = null;
switch (operation) {
case SOMA:
total = value1 + value2;
break;
case SUBTRACAO:
total = value1 - value2;
break;
case MULTIPLICACAO:
total = value1 * value2;
break;
case DIVISAO:
if (value2 == 0D) {
throw new IllegalArgumentException("Division by Zero!");
}
total = value1 / value2;
break;
default:
System.out.println("Operation undefined!");
}
return total;
}
Boolean isCharOperation(String value) {
return Operation.fromCharactere(value) != null;
}
}
enum Operation {
SOMA("+"),
SUBTRACAO("-"),
MULTIPLICACAO("*"),
DIVISAO("/");
private String value;
private Operation(String value) {
this.value = value;
}
public static Operation fromCharactere(String op) {
for (Operation operation : Operation.values() ) {
if (operation.value.equals(op)) {
return operation;
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment