Skip to content

Instantly share code, notes, and snippets.

@alexejVasko
Created March 22, 2016 13:24
Show Gist options
  • Save alexejVasko/4040f5c7ba4051ed9f12 to your computer and use it in GitHub Desktop.
Save alexejVasko/4040f5c7ba4051ed9f12 to your computer and use it in GitHub Desktop.
package calculator;
public class StringDoubleCalculating {
public enum Actions {
SUM,
SUBTRACTION,
MULTIPLY,
DIVIDE
}
public static char getActionSymbol(Actions action) {
switch (action) {
case SUM:
return '+';
case SUBTRACTION:
return '-';
case MULTIPLY:
return '*';
case DIVIDE:
return '/';
}
return ' ';
}
public static double precondition(String valueToEvaluate) {
try {
if (valueToEvaluate.contains("*") || valueToEvaluate.contains("/") ||
valueToEvaluate.contains("+") || valueToEvaluate.contains("-")) {
Actions currentAction = null;
int indexOfMultiply = valueToEvaluate.indexOf("*");
int indexOfDivide = valueToEvaluate.indexOf("/");
int indexOfSum = valueToEvaluate.indexOf("+");
int indexOfSubtraction = valueToEvaluate.indexOf("-");
if (indexOfMultiply > 0) {
currentAction = Actions.MULTIPLY;
} else if (indexOfDivide > 0) {
currentAction = Actions.DIVIDE;
} else if (indexOfSum > 0) {
currentAction = Actions.SUM;
} else if (indexOfSubtraction > 0) {
currentAction = Actions.SUBTRACTION;
} else {
System.err.println("");
}
char currentActionChar = getActionSymbol(currentAction);
int indexOfAction = valueToEvaluate.indexOf(currentActionChar);
String firstPart = valueToEvaluate.substring(0, indexOfAction).trim();
String secondPart = valueToEvaluate.substring(indexOfAction + 1).trim();
System.out.println("FIRST: " + currentActionChar + "|" + firstPart + "|" + currentAction);
System.out.println("SECOND: |" + secondPart + "|");
System.out.println("---------------------------------------");
double value1 = Double.parseDouble(firstPart);
double value2 = Double.parseDouble(secondPart);
double result = 0;
if ('*' == currentActionChar) {
result = value1 * value2;
}
if ('/' == currentActionChar) {
result = value1 / value2;
}
if ('+' == currentActionChar) {
result = value1 + value2;
}
if ('-' == currentActionChar) {
result = value1 - value2;
}
System.out.println("RESULT: " + result);
System.out.println();
return result;
} else {
System.err.println("Cannot recognize expression. Please try again.(ENTER)");
}
} catch (Exception e) {
System.out.println("Перехвачено исключение # некорректный ввод выражения #");
}
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment