我设计了一个 RPN 算法来计算给计算器求和的结果。我的 RPN 代码如下:
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;
}
}
}
如果我给代码做以下计算:
[3.0, 2.0, /, 8.0, 3.0, +, -, 2.0, /]
它给出以下输出:
[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
所以在处理 [1.5, 11.0, -, 2.0, /] 时会出现错误
但是,如果我最初给它以下计算:
[1.5, 11.0, -, 2.0, /]
它给出了正确的答案:
[1.5, 11.0, -, 2.0, /]
[-9.5, 2.0, /]
[-4.75]
有人可以帮忙吗:)
ps对不起这个长问题