【发布时间】:2014-07-01 14:30:11
【问题描述】:
我正在尝试编写用于后缀评估的代码,但我收到一个错误
java.lang.String 不能转换为 java.lang.Integer,问题出在行obj1=(int) calStack.topAndpop();。问题是我的 ArrayStack topAndpop() 方法返回 Object 类型为
public Object topAndpop() throws EmptyStackException{
Object returnPop;
if (isEmpty())
throw new EmptyStackException("Stack empty");
else{
returnPop=top();
pop();
}
return returnPop;
我应该能够将其转换为 int 类型。除了这一行之外,我看不到任何错误。请有人指出如何纠正这个问题
import java.lang.Math;
public class Calculate{
double result=0;
int obj1,obj2;
public Object cal(String expression) throws OverFlowException,EmptyStackException{
String[] array = expression.split("");//remember
// for (int i=0;i<array.length;i++)
// System.out.println(array[i]);
ArrayStack calStack=new ArrayStack(array.length);
for(int i=0;i<array.length;i++){
if(!(array[i].equals("+") || array[i].equals("-")||array[i].equals("/") || array[i].equals("*"))){
calStack.push(array[i]);
//calStack.print();
}
else {
obj1=(int) calStack.topAndpop();//check how this casting is done
obj2=(int)calStack.topAndpop();
result=calculate(obj2,obj1,array[i]);
System.out.println(result);
calStack.push(result);
}
}
return calStack.topAndpop();
}
public double calculate(int a,int b,String op){
if(op=="+")
return a+b;
else if(op=="-")
return a-b;
else if(op=="/")
return a/b;
else if (op=="^")
return Math.pow(a,b);
else
return a*b;
}
public static void main (String args[]) throws OverFlowException,EmptyStackException{
Calculate c=new Calculate();
System.out.println("result"+c.cal("623+-382/+*2^3"));
}
}
【问题讨论】:
-
尝试打印出你从堆栈中弹出的内容
标签: java data-structures stack