tokenoperator.java

来自「Java程序设计技巧与开发实例附书源代码。」· Java 代码 · 共 74 行

JAVA
74
字号

public class TokenOperator
    extends Token
{
  private static String OPERATORS = "+-/*^()";
  private static int[] PRECEDENCE = { 1, 1, 2, 2, 3, 0, 9};
  private String token;

  public TokenOperator(String _token) throws TokenException
  {
    if (OPERATORS.indexOf(_token) >= 0)
    {
      token = _token;
    }
    else
    {
      throw new TokenException("invalid operator: " + _token);
    }
  }

  public TokenNumeric evaluate(double num1, double num2) throws TokenException
  {
    if (token.equals("+"))
    {
      return new TokenNumeric(num2 + num1);
    }
    else if (token.equals("-"))
    {
      return new TokenNumeric(num2 - num1);
    }
    else if (token.equals("*"))
    {
      return new TokenNumeric(num2 * num1);
    }
    else if (token.equals("/"))
    {
      return new TokenNumeric(num2 / num1);
    }
    else if (token.equals("^"))
    {
      return new TokenNumeric(Math.pow(num2, num1));
    }
    else
    {
      throw new TokenException("invalid token, can not evaluate");
    }
  }

  public boolean isOpenParen()
  {
    return token.equals("(");
  }

  public boolean isCloseParen()
  {
    return token.equals(")");
  }

  public int order()
  {
    return PRECEDENCE[OPERATORS.indexOf(token)];
  }

  public static boolean isValidOp(char op)
  {
    return (OPERATORS.indexOf(op) >= 0);
  }

  public String toString()
  {
    return "Operator: " + token;
  }
}

⌨️ 快捷键说明

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