错误类型不兼容。后缀评估

Error incompatible types. Postfix evaluation

我的任务是创建一个使用数组和字符进行后缀计算的程序。 我遇到了问题

incompatible type: Object cannot be converted to 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);
  }
}

您应该将其转换为整数。

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

您仅使用堆栈来存储 Integer 值,因此我建议指定通用类型:

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

这样 st.pop() 的类型将是 Integer 并将自动装箱为 int

当您将其声明为 Stack(没有类型参数)时,pop() returns Object 不能转换为 int显式转换(在另一个答案中提供)。