Calculator.java 文件源码

java
阅读 31 收藏 0 点赞 0 评论 0

项目:antlr-examples 作者:
/**
 * Returns the value of the given expression.
 *
 * <p>For example, {@code evaluate("1+2")} returns {@code 3.0}, but {@code evaluate("1+")} throws
 * an exception.
 *
 * @param input the {@code String} to parse and evaluate
 * @return the value of the given expression
 * @throws IllegalArgumentException if {@code input} is an invalid expression
 */
public static double evaluate(String input) {
  CalculatorParser parser = ParserUtil.newParser(
      CalculatorLexer::new, CalculatorParser::new, input);
  ExpressionEvaluator evaluator = new ExpressionEvaluator();

  try {
    ParserUtil.parseAndWalk(parser::expression, evaluator);
  } catch (ParseCancellationException e) {
    throw new IllegalArgumentException("Invalid expression", e);
  }

  return evaluator.getValue();
}
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号