开发者

Stack Calculator: Trouble evaluating postfix expression because of casting issue

开发者 https://www.devze.com 2023-01-25 21:06 出处:网络
I\'m working on a homework assignment that asks me to create a calculator that changes the expression given to it from infix to postfix to then evaluate. I must do so using stacks but may choose any s

I'm working on a homework assignment that asks me to create a calculator that changes the expression given to it from infix to postfix to then evaluate. I must do so using stacks but may choose any stack implementation I want as long as I don't use the java.util.Stack from the JCF. I chose a referenced based stack.

The problem I'm having is in my evaluatePostfix method. In order to evaluate the expression I had to cast my operand variables as Integers but eclipse doesn't seem to like that. I keep getting a "java.lang.Character cannot be cast to java.lang.Integer" error. I'm not sure how to fix this issue. Does anyone have any insight?

Here is my code:

public class InfixToPostfixAndEvaluateCalculator {

  private String infix;
  private String postfix;
  private int result;

  public InfixToPostfixAndEvaluateCalculator() {
    infix=null;
    postfix=null;
    result=0;
  }

  public InfixToPostfixAndEvaluateCalculator(String infix) {
    this.infix=infix;
    postfix=null;
    result=0;
  }

  public String getInfix() {
    return infix;
  }
  public String getPostfix() {
    return postfix;
  }
  public int getresult() {
    return result;
  }
  public void setInfix(String infix) {
    this.infix=infix;
  }
  public void setP开发者_StackOverflowostfix(String postfix) {
    this.postfix=postfix;
  }

  public String toString() {
    return " Infix: "+infix+"\n Postfix: "+postfix+"\n Result: "+result+"\n";
  }


  public String infixToPostfix() { //Carrano 2nd ed. p.354
    //opStack is a stack of Character objects, such as '+','-','*','/', and ')'
    StackInterface opStack=new StackReferenceBased();
    String postfixExp=""; //the expression to be built in this method

    //for each character ch in the string infix
    for (int i=0; i<infix.length(); i++) {
      char ch=infix.charAt(i);
      switch (ch) {
        //if ch is an operator
        case '+': case '-': case '*': case '/':
          while ( (!opStack.isEmpty()) 
            && (!opStack.peek().equals('('))
            && (precedence(ch) <= precedence((Character)opStack.peek()))){
           postfixExp = postfixExp + opStack.pop();
          }
          opStack.push(ch);
          break;
        case '(': //add to stack
          opStack.push(ch);
          break;
        case ')': //start popping things off the stack until you find opening parenthesis, use peak
        while (!((Character)opStack.peek()).equals('(')){
          postfixExp = postfixExp + opStack.pop();

          }//end while
          opStack.pop();
          break;
        default: //ch is an operand
          postfixExp = postfixExp + ch;
          break;
      }//end of switch
    }//end of for
    System.out.println("End of for loop.");
    //append to postfixExp the operators remaining in the stack
    while (! opStack.isEmpty()) {
      postfixExp=postfixExp+((Character) opStack.pop()).charValue(); 
    }//end of while

    postfix=postfixExp; //update the instance variable
    return postfixExp;
  }//end of infixToPostfix()

  //little helper function to determine precedence value of an operator
  // *,/ have value of, say 20
  // +,- have value of, say 10
  private int precedence(char ch) {
   int prec = 20;
   int prec2 = 10;
    if (ch == '*' || ch == '/'){
     return prec;
    }
   if (ch == '+' || ch == '-'){
    return prec2;
   }
   return -1;
    }


  public int evaluatePostfix() { //Carrano 2nd ed. pp.350-351
    //valueStack is a stack of Integer objects:
    StackInterface valueStack=new StackReferenceBased();
    //variables for the operands:
    int operand1, operand2;
    //for each character ch in the string postfix
    for (int i=0; i<postfix.length(); i++) {
      char ch=postfix.charAt(i);
      switch (ch) {
        //if ch is an operator
        case '+':
          operand2 = (Integer)valueStack.pop();
          operand1 = (Integer)valueStack.pop();
          result = operand1 + operand2;
          valueStack.push(result);
          break;
        case '-':
          operand2 = (Integer)valueStack.pop();
          operand1 = (Integer)valueStack.pop();
          result = operand1 - operand2;
          valueStack.push(result);
          break;
        case '*':
          operand2 = (Integer)valueStack.pop();
          operand1 = (Integer)valueStack.pop();
          result = operand1 * operand2;
          valueStack.push(result);
          break;
        case '/':
          operand2 = (Integer)valueStack.pop();
          operand1 = (Integer)valueStack.pop();
          result = operand1 / operand2;
          valueStack.push(result);
          break;
        default: //ch is an operand
          valueStack.push(ch);
          break;
      }//end of switch
    }//end of for
    //at the end, the value of the expression will be on the top of the stack
    result=((Integer) valueStack.pop()).intValue();
    return result;
  }//end of evaluatePostfix()

} // end StackTest


Yes, you cannot cast Character to Integer.

To do that you can use,

Integer.parseInt(String.valueOf(valueStack.pop()));

parseInt doesn't take Character as argument so, you have to convert first into String and then to Integer.


there is a function to get the numeric int value of a Unicode character

Character.getNumericValue( ch );


hopefully the StackInterface supports type-information
this would prevent dozens of (Integer)-casts

StackInterface<Integer> valueStack = new StackReferenceBased<Integer>();
0

精彩评论

暂无评论...
验证码 换一张
取 消