2014-05-13 43 views
0

我試圖寫一個後綴評估代碼,但我得到一個錯誤的進行評價,採用堆在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")); 

} 

}

+0

嘗試打印出您要從堆棧彈出的內容 – Kakarot

回答

1

而不是

obj1=(int) calStack.topAndpop();//check how this casting is done 
obj2=(int)calStack.topAndpop(); 

用途:

obj1 = Integer.parseInt((String)calStack.topAndpop()); 
obj2 = Integer.parseInt((String)calStack.topAndpop()); 
0

你有一個以上的問題,第一個String平等 -

public double calculate(int a,int b,String op){ 
    if(op.equals("+")) // <-- .equals! Not == 
    return a+b; 
    else if(op.equals("-")) 
    return a-b; 
    else if(op.equals("/")) 
    return a/b; 
    else if(op.equals("^")) 
    return Math.pow(a,b); 
    else 
    return a*b; 
} 

接下來,因爲你的站CK並不顯得generic,你應該叫Integer.parseInt(String)

obj1 = Integer.parseInt(calStack.topAndpop().toString()); 
0

的問題是在您檢查符號if條件,在這個你已經錯過了^符號:

  if(!(array[i].equals("+") || array[i].equals("-") 
       ||array[i].equals("/") || array[i].equals("*"))){ 

添加^符號的條件如下,您的代碼將起作用:

  if(!(array[i].equals("+") 
       || array[i].equals("-") 
       ||array[i].equals("/") 
       || array[i].equals("*")) 
       || array[i].equals("^"))){ 

      // do something 
      } 
+0

謝謝發現帖子後 –

+0

這是問題的原因..或者是別的東西? – Kakarot