listpostfixevaluator.java

来自「一个普通的计算器程序」· Java 代码 · 共 72 行

JAVA
72
字号
//************************************************************//  ListPostfixEvaluator.java       Authors:  Lewis/Chase//  //  Provides an evaluator for integer postfix expressions//  presented as a list.//************************************************************import jss2.*;import java.util.Iterator;public class ListPostfixEvaluator{  /**********************************************************    Constructor  **********************************************************/  public ListPostfixEvaluator()  {    }      /**********************************************************    Returns the result of a postfix expression  **********************************************************/  public int evaluate(ArrayUnorderedList<String> tokenList)  {    ArrayStack<Integer> inStack = new ArrayStack<Integer>();    int result, toPush=0,operand1=0, operand2=0;    char tempChar;    String tempToken;        while (tokenList.size() > 0)    {      tempToken = tokenList.removeFirst();            /** operator of length greater than 1 */      if(tempToken.length()>1)        inStack.push(new Integer(Integer.parseInt(tempToken)));            else if(tempToken.length()==1)      {        tempChar = tempToken.charAt(0);                /** if operator */        if(tempChar >= '0' && tempChar <= '9')              inStack.push(new Integer(Integer.parseInt(tempToken)));                /** if operand */        else if( tempToken.equals("*")|| tempToken.equals("/") ||                  tempToken.equals("+")|| tempToken.equals("-") )        {          /** get operator/operands for calculation */          operand2 = inStack.pop();          operand1 = inStack.pop();          tempChar = tempToken.charAt(0);                    /** calculate */          switch (tempChar)           {            case '*': toPush = operand1 * operand2; break;            case '/': toPush = operand1 / operand2; break;            case '+': toPush = operand1 + operand2; break;             case '-': toPush = operand1 - operand2; break;            }                    inStack.push(new Integer(toPush));        }      }    }        return (inStack.pop());  }} 

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?