I'm trying to create a Java calculator that takes in a formula formatted with spaces in between each character and within parentheses, for example, ( 3 + 2 / 4 * 1 ). I've gotten it to calculate left to right, but now I need to make it work according to order of operations (multiplication/division first, then addition/subtraction). I've been using .split to get each character alone, here is my code currently.
public double getDoubleValue()
{
String formulaStr = super.fullCellText();
formulaStr = formulaStr.substring(2,formulaStr.length()-1);
String[] formulaSplit = formulaStr.split(" ");
double result = Double.parseDouble(formulaSplit[0]);
for(int i = 0; i < formulaSplit.length; i++)
{
if(formulaSplit[i].equals("*"))
result *= Double.parseDouble(formulaSplit[i+1]);
else if(formulaSplit[i].equals("/"))
result /= Double.parseDouble(formulaSplit[i+1]);
else if(formulaSplit[i].equals("+"))
result += Double.parseDouble(formulaSplit[i+1]);
else if(formulaSplit[i].equals("-"))
result -= Double.parseDouble(formulaSplit[i+1]);
}
return result;
}
I tried splitting on the +/- characters, but my code started to get very overly complicated. What would be the simplest way to do this, ideally keeping close to the structure of the initial code?