我試圖寫一個後綴評估代碼,但我得到一個錯誤的進行評價,採用堆在Java後綴表達式
java.lang.String中不能轉換爲java.lang.Integer的,問題是在線obj1=(int) calStack.topAndpop();
。問題是我ArrayStack topAndpop()方法返回一個對象型作爲
public Object topAndpop() throws EmptyStackException{
Object returnPop;
if (isEmpty())
throw new EmptyStackException("Stack empty");
else{
returnPop=top();
pop();
}
return returnPop;
,我應該能夠將其轉換成INT type.I什麼都看不到從該行錯分開。有人可以指點我怎麼改正這個請
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"));
}
}
嘗試打印出您要從堆棧彈出的內容 – Kakarot