Имате проблеми с прехвърлянето на номер на стеков обект към int (Java)

Пиша програма, която преобразува израз от инфикс в постфикс. Нямам частта за преобразуване, но когато става въпрос за оценка на постфиксния израз, срещам проблеми с преобразуването от 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;
}
    }

person Jonny    schedule 07.04.2014    source източник
comment
Първо, не използвайте сурови типове.   -  person Sotirios Delimanolis    schedule 07.04.2014


Отговори (2)


Можете да разрешите това чрез кастинг към int. Обърнете внимание, че int и Integer не са едно и също:

Integer x1 = (int) stack2.pop();
Integer x2 = (int) stack2.pop();
person Christian    schedule 07.04.2014
comment
Благодаря, получи се! Но сега получавам грешката Exception in thread main java.util.EmptyStackException? Някаква идея защо? - person Jonny; 07.04.2014
comment
Това означава, че се опитвате да извадите елемент от празен стек, което не е възможно. - person Christian; 07.04.2014

не е необходимо кастинг чрез използване на тип-информация

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();
  …

между другото: програмата е синтактично грешна, защото поставя само една стойност в стека

person Kaplan    schedule 17.10.2019