I have designed a RPN algorithm to compute the result of a sum given to a calculator. My code for the RPN is as follows:
import java.util.ArrayList;
public class RPNCalculator {
String operator;
double number_1;
double number_2;
double result;
public int length_change;
public void calculateResult(ArrayList<Object> outputQueueArray)
{
int length = outputQueueArray.size();
length_change = length;
int i;
int b;
int a;
for(b = 0; b < length; b++){
for(i = 0; i < length_change; i++){
if(outputQueueArray.get(i).equals("+") || outputQueueArray.get(i).equals("-") || outputQueueArray.get(i).equals("/") || outputQueueArray.get(i).equals("*")){
a = i - 2;
operator = (String) outputQueueArray.remove(i) ;
number_1 = (double) outputQueueArray.remove(i - 1);
number_2 = (double) outputQueueArray.remove(i - 2);
outputQueueArray.add(a,useOperator(number_1, number_2, operator));
length_change = outputQueueArray.size();
System.out.println(outputQueueArray);
}
}
}
}
public double useOperator(double number_1, double number_2, String operator)
{
if(operator.equals("+")){
return number_2 + number_1;
}
else if(operator.equals("-")){
return number_2 - number_1;
}
else if(operator.equals("/")){
return number_2 / number_1;
}
else if(operator.equals("*")){
return number_2 * number_1;
}
else{
return 0;
}
}
}
if i give the code the following calculation to do:
[3.0, 2.0, /, 8.0, 3.0, +, -, 2.0, /]
it gives the following output:
[1.5, 8.0, 3.0, +, -, 2.0, /]
[1.5, 11.0, -, 2.0, /] java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
So the error occurs when processing [1.5, 11.0, -, 2.0, /]
However if i initially give it the following calculation to do:
[1.5, 11.0, -, 2.0, /]
It gives the correct answer:
[1.5, 11.0, -, 2.0, /]
[-9.5, 2.0, /]
[-4.75]
Could anyone help with this :)
p.s. sorry for the long question
You better use a stack.
This way the algorithm should be significantly faster, since removing elements from position i of an ArrayList L requires O(L.size() - i) time.
Example execution for
:
operands = []
o = 3.0
:operands = [3.0]
o = 2.0
:operands = [3.0, 2.0]
o = "/"
:operands
:operands = []; operand1 = 3.0; operand2 = 2.0
(operand1 / operand2)
to stack:operands = [1.5]
o = 8.0
:operands = [1.5, 8.0]
o = 3.0
:operands = [1.5, 8.0, 3.0]
o = "+"
:operands
:operands = [1.5]; operand1 = 8.0; operand2 = 3.0
(operand1 + operand2)
to stack:operands = [1.5, 11.0]
o = "-"
:operands
:operands = []; operand1 = 1.5; operand2 = 11.0
(operand1 - operand2)
to stack:operands = [-9.5]
o = 2.0
:operands = [-9.5, 2.0]
o = "+"
:operands
:operands = []; operand1 = -9.5; operand2 = 2.0
(operand1 + operand2)
to stack:operands = [-7.5]