我的任务是使用array和char创建一个用于后缀评估的程序。 我遇到了问题
不兼容类型:无法将对象转换为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);
}
}
答案 0 :(得分:1)
您只使用堆栈存储Integer
值,因此我建议指定泛型类型:
Stack<Integer> st = new Stack<>();
这样st.pop()
将会有Integer
类型,并会自动退回到int
。
当您将其声明为Stack
(没有类型参数)时,pop()
会返回Object
,如果没有显式转换,则无法转换为int
回答)。
答案 1 :(得分:0)
您应该将其转换为整数。
block