package book.string;
public class ExpressionParser {
public static final int NONE_TOKEN = 0;
public static final int DELIMITER_TOKEN = 1;
public static final int VARIABLE_TOKEN = 2;
public static final int NUMBER_TOKEN = 3;
// 四种错误类型
public static final int SYNTAX_ERROR = 0;
public static final int UNBALPARENS_ERROR = 1;
public static final int NOEXP_ERROR = 2;
public static final int DIVBYZERO_ERROR = 3;
public static final String[] ERROR_MESSAGES = { "systax Error ",
"Unbalanced parentheses", "no Expression present",
"Division by Zero" };
public static final String EOE = "\0";// 结束标志
private String exp;
private int expIndex;
private String token;
private int tokenType;
private double vars[] = new double[26];
public double evaluate(String expStr) throws Exception {
double result;
this.exp = expStr;
this.expIndex = 0;
this.getToken();
if (this.token.equals(EOE)) {
this.handleError(NOEXP_ERROR);
}
result = this.parseAssign();
if (!this.token.equals(EOE)) {
this.handleError(SYNTAX_ERROR);
}
return result;
}
public double parseAssign() throws Exception {
double result;
int varIndex;
String oldToken;
int oldTokenType;
if (this.tokenType == VARIABLE_TOKEN) {
oldToken = new String(this.token);
oldTokenType = this.tokenType;
varIndex = Character.toUpperCase(this.token.charAt(0)) - 'A';// ?????????????????????????
this.getToken();
if (!this.token.equals("=")) {
this.putBack();
this.token = new String(oldToken);
this.tokenType = oldTokenType;
} else {
this.getToken();
result = this.parseAddOrSub();
this.vars[varIndex] = result;
return result;
}
}
return this.parseAddOrSub();
}
public double parseAddOrSub() throws Exception {
char op;
double result;
double partialResult;
result = this.parseMulOrDiv();
while ((op = this.token.charAt(0)) == '+' || op == '-') {
this.getToken();
partialResult = this.parseMulOrDiv();
switch (op) {
case '-':
result = result - partialResult;
break;
case '+':
result = result + partialResult;
break;
}
}
return result;
}
public double parseMulOrDiv() throws Exception {
char op;
double result;
double partialResult;
result = this.parseExponent();
while ((op = this.token.charAt(0)) == '*' || op == '/' || op == '%') {
this.getToken();
partialResult = this.parseExponent();
switch (op) {
case '*':
result = result * partialResult;
break;
case '/':
if (partialResult == 0.0) {
this.handleError(DIVBYZERO_ERROR);
}
result = result / partialResult;
break;
case '%':
if (partialResult == 0.0) {
this.handleError(DIVBYZERO_ERROR);
}
result = result % partialResult;
break;
}
}
return result;
}
public double parseExponent() throws Exception {
double result;
double partialResult;
double ex;
int t;
result = this.parseUnaryOperator();
if (this.token.equals("^")) {
this.getToken();
partialResult = this.parseExponent();
ex = result;
if (partialResult == 0.0) {
result = 1.0;
} else {
for (t = (int) partialResult - 1; t > 0; t--) {
result = result * ex;
}
}
}
return result;
}
public double parseUnaryOperator() throws Exception {
double result;
String op;
op = "";
if ((this.tokenType == DELIMITER_TOKEN) && this.token.equals("+")
|| this.token.equals("-")) {
op = token;
this.getToken();
}
result = this.parseBracket();
if (op.equals("-")) {
result = -result;
}
return result;
}
public double parseBracket() throws Exception {
double result;
if (this.token.equals("(")) {
this.getToken();
result = this.parseAddOrSub();
if (!this.token.equals(")")) {
this.handleError(UNBALPARENS_ERROR);
}
this.getToken();
} else {
result = this.parseAtomElement();
}
return result;
}
public double parseAtomElement() throws Exception {
double result = 0.0;
switch (this.tokenType) {
case NUMBER_TOKEN:
try {
result = Double.parseDouble(this.token);
} catch (NumberFormatException exc) {
this.handleError(SYNTAX_ERROR);
}
this.getToken();
break;
case VARIABLE_TOKEN:
result = this.findVar(token);
this.getToken();
break;
default:
this.handleError(SYNTAX_ERROR);
break;
}
return result;
}
public double findVar(String vname) throws Exception {
if (!Character.isLetter(vname.charAt(0))) {
handleError(SYNTAX_ERROR);
return 0.0;
}
return vars[Character.toUpperCase(vname.charAt(0)) - 'A'];
}
public void putBack() {
if (this.token == EOE) {
return;
}
for (int i = 0; i < this.token.length(); i++) {
this.expIndex--;
}
}
public void handleError(int errorType) throws Exception {
throw new Exception(ERROR_MESSAGES[errorType]);
}
public void getToken() {
this.tokenType = NONE_TOKEN;
this.token = "";
if (this.expIndex == this.exp.length()) {
this.token = EOE;
return;
}
while (this.expIndex < this.exp.length()
&& Character.isWhitespace(this.exp.charAt(this.expIndex))) {
++this.expIndex;
}
if (this.expIndex == this.exp.length()) {
this.token = EOE;
return;
}
char currentChar = this.exp.charAt(this.expIndex);
if (isDelim(currentChar)) {
this.token += currentChar;
this.expIndex++;
this.tokenType = DELIMITER_TOKEN;
} else if (Character.isLetter(currentChar)) {
while (!isDelim(currentChar)) {
this.token += currentChar;
this.expIndex++;
if (this.expIndex >= this.exp.length()) {
break;
} else {
currentChar = this.exp.charAt(this.expIndex);
}
}
this.tokenType = VARIABLE_TOKEN;
} else if (Character.isDigit(currentChar)) {
while (!isDelim(currentChar)) {
this.token += currentChar;
this.expIndex++;
if (this.expIndex >= this.exp.length()) {
break;
} else {
currentChar = this.exp.charAt(this.expIndex);
}
}
this.tokenType = NUMBER_TOKEN;
} else {
this.token = EOE;
return;
}
}
public boolean isDelim(char c) {
if ((" +-*/%^=()".indexOf(c) != -1))
return true;
return false;
}
public static void main(String[] srgs) throws Exception {
ExpressionParser test = new ExpressionParser();
String exp1 = "(4-2)*5/2-6";
System.out.println(exp1 + "=" + test.evaluate(exp1));
}
}
java 写的 用优先函数分析 数学表达式的程序
4星 · 超过85%的资源 需积分: 9 46 浏览量
2009-04-29
16:05:29
上传
评论
收藏 11KB RAR 举报
liu4306518
- 粉丝: 7
- 资源: 5
最新资源
- ### 微信小程序概念、使用技巧、优缺点
- 文件I/O基础-I.MX6U嵌入式Linux C应用编程学习笔记基于正点原子阿尔法开发板
- 基于QT的翻金币小游戏
- 餐厅点餐系统(springboot+ssm+html+mysql)含演示视频.zip
- A non-local algorithm for image denoising
- python实现基于VMD-Attention-LSTM的时间序列预测模型项目源码(高分项目).zip
- ### 华为OD(OceanBase Distributed Database)概念、使用技巧、优缺点
- ubuntu的概要介绍与分析
- 基于PHP网络数据包分析工具设计.zip
- 红外图像非均匀性校正算法-红外图像非均匀性校正数据集-基于深度学习的红外图像非均匀性校正-红外图像去噪算法和数据集
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
- 1
- 2
前往页