I am currently working on building a calculator using Java and JavaFX to practice my coding skills. I wrote the following methods to evaluate a given expression.
What can I improve? Is there anything you would recommend me to change to optimize my program?
public static String evaluate(String expression) {
char[] tokens = expression.toCharArray();
List<String> list = new ArrayList<>();
String s = "";
String operator = "";
String firstNum = "";
String secondNum = "";
boolean operationOnQueue = false;
for (int i = 0; i < tokens.length; i++) {
if (Character.isDigit(tokens[i])) {
s += Character.toString(tokens[i]);
} else {
list.add(s);
list.add(Character.toString(tokens[i]));
if (operationOnQueue) {
operationOnQueue = false;
secondNum = s;
list.set(list.lastIndexOf(firstNum), eval(firstNum, operator, secondNum));
list.remove(list.lastIndexOf(operator));
list.remove(list.lastIndexOf(secondNum));
}
if (tokens[i] == '*' || tokens[i] == '/') {
operationOnQueue = true;
operator = Character.toString(tokens[i]);
firstNum = list.get(list.lastIndexOf(operator) - 1);
}
s = "";
}
if (i == tokens.length - 1 && s.length() > 0) {
list.add(s);
if (list.get(list.size() - 2).equals("*") || list.get(list.size() - 2).equals("/")) {
firstNum = list.get(list.size() - 3);
operator = list.get(list.size() - 2);
secondNum = list.get(list.size() - 1);
list.set(list.size() - 3, eval(firstNum, operator, secondNum));
list.remove(list.size() - 2);
list.remove(list.size() - 1);
}
}
}
while (list.size() > 1) {
firstNum = list.get(0);
operator = list.get(1);
secondNum = list.get(2);
list.set(0, eval(firstNum, operator, secondNum));
list.remove(2);
list.remove(1);
}
return list.get(0);
}
public static String eval(String a, String operator, String b) {
double r = 0;
switch (operator) {
case "/":
r += Double.parseDouble(a) / Double.parseDouble(b);
break;
case "*":
r += Double.parseDouble(a) * Double.parseDouble(b);
break;
case "-":
r += Double.parseDouble(a) - Double.parseDouble(b);
break;
case "+":
r += Double.parseDouble(a) + Double.parseDouble(b);
break;
}
return Double.toString(r);
}
These are the results of my tests. The first line is the string inputted, along with the answer to the expression. The second line is the output of the program.
8+4/2+10*3+5*10 = 90
90.0
60*60+8+384/7/4-44*26 = 2477.71
2477.714285714286
64/16*18-51*7+5 = -280
-280.0
64/16*18-5100*7+5 = -35623
-35623.0
7325+92+44/4+57-84 = 7401
7401.0
14+54/9+1 = 21
21.0
7*4/7+9+12*3 = 49
49.0