我正在编写一个程序,将表达式从中缀转换为后缀。我有转换部分,但在评估后缀表达式时,我遇到了使用堆栈从char转换为int的问题。
我一直收到错误:“线程中的异常”main“java.lang.ClassCastException:java.lang.Character无法强制转换为java.lang.Integer”
可能在下面代码的这部分问题出现了,但我不确定:
Integer x1 = (Integer)stack2.pop();
Integer x2 = (Integer)stack2.pop();
public class Calc {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Please enter your infix expression: ");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String postfix = "";
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < input.length(); i++){
char subject = input.charAt(i);
if (subject == '*'||subject == '+'||subject == '-'||subject == '/'){
while ((stack.empty() == false) && (order(stack.peek()) >= order(subject)))
postfix += stack.pop() + " ";
stack.push(subject);
}
else if(subject == '(')
{
stack.push(subject);
}
else if(subject == ')')
{
while(stack.peek().equals('(') == false){
postfix += stack.pop() + " ";
}
stack.pop();
}
else{
if((Character.isDigit(subject) == true) && ((i + 1) < input.length()) && (Character.isDigit(input.charAt(i+1)) == true))
{
postfix += subject;
}
else if(Character.isDigit(subject))
{
postfix += subject + " ";
}
else
{
postfix += subject;
}
}
}
postfix += stack.pop();
System.out.println("Your post-fix expression is: " + postfix);
char subject2;
int yeah;
Stack stack2 = new Stack();
for (int j = 0; j < postfix.length(); j++){
subject2 = postfix.charAt(j);
if(Character.isDigit(subject2) == true){
stack2.push(subject2);
}
if(subject2 == ' '){
continue;
}
else{
Integer x1 = (Integer)stack2.pop();
Integer x2 = (Integer)stack2.pop();
if (subject2 == '+'){
yeah = x1 + x2;
}
if (subject2 == '-'){
yeah = x1 - x2;
}
if (subject2 == '*'){
yeah = x1 * x2;
}
if (subject2 == '/'){
yeah = x1 / x2;
}
else {
yeah = 0;
}
}
}
yeah = (int) stack2.pop();
System.out.println("The result is:" + yeah);
}
static int order(char operator)
{
if(operator == '+' || operator =='-')
return 1;
else if(operator == '*' || operator == '/')
return 2;
else
return 0;
}
}
答案 0 :(得分:2)
您可以通过转换为int
来解决此问题。请注意,int
和Integer
为not the same:
Integer x1 = (int) stack2.pop();
Integer x2 = (int) stack2.pop();
答案 1 :(得分:0)
使用类型信息无需强制转换
Stack<Integer> stack2 = new Stack<Integer>();
…
if(Character.isDigit(subject2) == true){
stack2.push( Character.getNumericValue( subject2 ) );
}
…
防止出现空堆栈异常我更喜欢poll
胜过pop
因此更容易检查错误状态
例如。 if( x1 == null ) System.err.println( "Your error message" );
Deque<Integer> stack2 = new ArrayDeque<Integer>();
…
Integer x1 = stack2.poll();
Integer x2 = stack2.poll();
…
btw:程序在语法上是错误的,因为它仅将一个值放在堆栈上