import java.util.regex.*;
import java.util.*;
/**
* 利用正则式计算表达式的值
*
* @author: Eastsun
* @version: 0.5 07.2.26
*/
public class Calculate {
public static final String NUM_PATTERN = // 数字的匹配模式
"(?:(?<=[//+//-//*//(/]|^)[+-]|)" // 前缀判断,判断前面的+-是否为符号
+ "(?:" // 数字及小数点部分, 0. 以及 .0 都是合法的数字
+ "(?://d*//.)?//d+|" // .0 的情形
+ "//d+(?://.//d*)?" // 0. 的情形
+ ")" + "(?!//d|//.)"; // 边界条件
public static final String BRA_PATTERN = "//((NUM)//)".replace("NUM",
NUM_PATTERN);
public static final String ADD_PATTERN = "(NUM)//+(NUM)".replace("NUM",
NUM_PATTERN);
public static final String SUB_PATTERN = "(NUM)-(NUM)".replace("NUM",
NUM_PATTERN);
public static final String MUL_PATTERN = "(NUM)//*(NUM)".replace("NUM",
NUM_PATTERN);
public static final String DIV_PATTERN = "(NUM)/(NUM)".replace("NUM",
NUM_PATTERN);
public static final Pattern BRA = Pattern.compile(BRA_PATTERN);
public static final Pattern ADD_OR_SUB = Pattern
.compile("(?<=[^//+//-//*/]|^)(?:" + ADD_PATTERN + "|"
+ SUB_PATTERN + ")(?=[^//*/]|$)");
public static final Pattern MUL_OR_DIV = Pattern.compile("(?<![//*/])(?:"
+ MUL_PATTERN + "|" + DIV_PATTERN + ")");
private static double operator(Matcher m, int index) {
index = index * 2;
double a, b;
if (m.group(1) != null) {
a = Double.parseDouble(m.group(1));
b = Double.parseDouble(m.group(2));
} else {
index++;
a = Double.parseDouble(m.group(3));
b = Double.parseDouble(m.group(4));
}
double r = 0.0;
switch (index) {
case 0:
r = a + b;
break;
case 1:
r = a - b;
break;
case 2:
r = a * b;
break;
case 3:
r = a / b;
break;
}
return r;
}
public static double eval(String str) {
StringBuilder sb = new StringBuilder(str.replaceAll("//s+", ""));
while (true) {
Matcher m = BRA.matcher(sb);
if (m.find()) {
sb.replace(m.start(), m.end(), m.group(1));
} else {
int index = 1;
m = MUL_OR_DIV.matcher(sb);
if (!m.find()) {
index--;
m = ADD_OR_SUB.matcher(sb);
if (!m.find())
break;
}
sb.replace(m.start(), m.end(), "" + operator(m, index));
}
}
return Double.parseDouble(sb.toString());
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.print("/nEnter a expression :");
String str = scan.next();
if (str.equals("exit"))
break;
System.out.print(str + " = " + eval(str));
}
}
}