2017-08-14 69 views
0

我的任務是使用array和char爲postfix評估創建一個程序。 我遇到問題錯誤不兼容的類型。 Postfix評估

不兼容的類型:對象不能轉換爲int。

這裏是我的代碼:

import java.util.*; 
public class StackPostfixEva { //class name 
    public static void main(String args[]) { 

    Scanner key = new Scanner(System.in); //initialize scanner 
    char[] postfix = new char[10]; //creating array 

    System.out.println("Please enter postfix expression. Enter '#' if you have finish entering postfix expression "); //instruction command 
    int i; //initialize variable 
    for (i = 0; i <= postfix.length; i++) { //loop for receiving input 
     postfix[i] = key.next().charAt(i); //input command 
     if (postfix[i] == '#') { //to indicate the end 
     break; 
     } 
    } 
    System.out.println("The postfix expression are:"); //to print postfix 
    expression 
    for (i = 0; i <= postfix.length; i++) { 
     System.out.println(postfix[i]); 
    } 
    Stack st = new Stack(); //creating stack 
    int result, ch1, ch2; //initialize variable 
    for (i = 0; i <= postfix.length; i++) { //loop for scanning each char 
     if (postfix[i] >= '0' && postfix[i] <= '9') { //to determine operand 
     st.push((int) postfix[i] - '0'); //push operand 
     } 
     else 
     { //execution if operator found 
     ch1 = st.pop(); //problem here 
     ch2 = st.pop(); //problem here 
     switch (postfix[1]) { 
      case '+': 
      result = ch2 + ch1; 
      break; 
      case '-': 
      result = ch2 - ch1; 
      break; 
      case '*': 
      result = ch2 * ch1; 
      break; 
      case '/': 
      result = ch2/ch1; 
      break; 
      case '%': 
      result = ch2/ch1; 
      break; 
      default: 
      result = 0; 
     } //end switch 
     st.push(result); 
     } //end else 
    } //end for 
    result = st.pop(); //problem here 
    System.out.println(result); 
    } 
} 

回答

1

您只使用您的堆棧來存儲Integer值,所以我建議指定泛型類型:

Stack<Integer> st = new Stack<>(); 

這樣st.pop()將有類型Integer,將autoboxed到int

當你只是聲明爲Stack(無類型參數),pop()回報Object這是無法轉換爲int沒有明確的轉換(在另一個答案提供)。

+0

感謝您的解決方案。但是現在我遇到了ArrayIndexOutOfBound異常。 >。< –

+0

用ArrayIndexOutOfBound異常完成,但EmptyStack異常後來。 –

+0

你需要調試你的代碼,看看爲什麼在一個空棧上調用'pop()'操作。任何像樣的IDE(例如,IDEA,Eclipse,Netbeans)都包含一個調試器,它可以在執行代碼時逐步執行代碼,並查看變量發生的情況。 –

0

你應該將其轉換爲整數。

ch1 = Integer.parseInt(st.pop()); 
ch2 = Integer.parseInt(st.pop()); 
+0

此解決方案不起作用。它只是給出了同樣的錯誤。 –