我是编码新手。尝试用Java编写一个evaluatePostfix函数。 我不断收到错误:
incompatible types: int cannot be converted to Character stack.push(eval(token, a, b));
这是一项将中缀表示法转换为后缀的学校作业。
以下是我的代码块:
private static int evalPostfix(String postfix){
char token = ' ';
int a;
int b;
Queue<Character> postfixQ = new Queue<>();
for (char i : postfix.toCharArray()) {
postfixQ.enqueue(i);
}
Stack<Character> stack = new Stack<>();
while (!postfixQ.isEmpty()){
token = postfixQ.dequeue();
if (isOperand(token)){
stack.push(token);
}
else {
a = stack.pop();
b = stack.pop();
stack.push(eval(token, a, b));
}
}
if(!stack.isEmpty()){
return stack.pop();
}
else {
System.out.println("Invalid postfix expression");
}
}
函数接受后缀表达式并计算结果。
这是我的评估函数:
private static int eval(char op, int a, int b){
int result = -1;
if (op == '+'){
return a + b;
}
else if (op == '-'){
return a - b;
}
else if (op == '*'){
return a * b;
}
else if (op == '/'){
return a / b;
}
else if (op == '^')
return (int)Math.pow(a, b);
return result;
}
最佳答案
问题在于方法 eval
返回 int
,然后您尝试将结果插入 Stack<Character>
.
我不完全确定你想在这里做什么,但这不会编译,因为 int
不能直接转换为Character
.
您可以通过将显式转换插入 char
来解决编译问题
stack.push((char)eval(token, a, b));
但这会转换 eval
的结果为 char
范围内的值,对于很容易超出 [0..65535] range of char
的值,这可能不是您想要做的.
关于java - 如何正确编写evaluatePostfix函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54249038/