gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:22:17 25 4
gpt4 key购买 nike

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

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);
}
}

最佳答案

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

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

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

当你刚刚将其声明为 Stack 时(没有类型参数),pop()返回Object它不能转换为 int没有明确的类型转换(在另一个答案中提供)。

关于java - 错误不兼容的类型。后缀评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45680953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com