堆栈计算器:由于转换问题而无法评估后缀表达式

发布于 2024-10-03 01:22:27 字数 4579 浏览 2 评论 0原文

我正在做一项家庭作业,要求我创建一个计算器,将给出的表达式从中缀更改为后缀,然后进行评估。我必须使用堆栈来执行此操作,但只要不使用 JCF 中的 java.util.Stack,就可以选择我想要的任何堆栈实现。我选择了基于引用的堆栈。

我遇到的问题是在我的valuatePostfix 方法中。为了计算表达式,我必须将操作数变量转换为整数,但 Eclipse 似乎不喜欢这样。我不断收到“java.lang.Character 无法转换为 java.lang.Integer”错误。我不知道如何解决这个问题。有人有任何见解吗?

这是我的代码:

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 setPostfix(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

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 setPostfix(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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半窗疏影 2024-10-10 01:22:27

是的,您不能将字符转换为整数。

为此,您可以使用

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

parseInt 不将字符作为参数,因此您必须先转换为字符串,然后再转换为整数。

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.

指尖凝香 2024-10-10 01:22:27

有一个函数可以获取数字 int Unicode字符的值

Character.getNumericValue( ch );

希望StackInterface支持类型-信息
这将阻止数十个 (Integer) 强制转换

StackInterface<Integer> valueStack = new StackReferenceBased<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>();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文