我试图用Java创建一个计算器。我有一个字符串参数可能看起来像这样:
23+48*26-4*sqrt26-exp.3-20%*25+56/33
我不知道如何创建仅匹配非字母字符或字符串的RegEx。我想要的结果是这样的:
String result = "+,*,-,*,sqrt,-,exp,-,%,*,+,/";
我使用字符串是因为我想允许用户在点击=
符号之前修改输入。
Bellow是我用来计算结果的函数:
public double calculate(String operations) {
String numberPattern = "[-+]?([0-9]*\\.[0-9]+|[0-9]+)";
String operatorsPattern = "";
Pattern number = Pattern.compile(numberPattern);
Matcher matcher = number.matcher(operations);
while(matcher.find()) {
double num1 = Double.parseDouble(matcher.group(1));
String operator = operator(operations);
// stergerea operatorului din string
operations = operations.substring(operator.length()+1);
if(!operator.equals("=")) {
result = result(result, num1, operator);
} else {
return result;
}
}
return result;
}
运算符函数是这样的:
private String operator(String string) {
String op = "";
String toFind = "[\\D]";
Pattern pattern = Pattern.compile(toFind);
Matcher matcher = pattern.matcher(string);
op = matcher.group(1);
return op;
}
答案 0 :(得分:-1)
首先需要以反向波兰表示法转换表达式: 5 +((1 + 2)×4)-3 = 5 1 2 + 4×+ 3 -
对于此任务,您可以使用Shunting-yard algo
然后你可以使用Post fix algorithm来评估表达式
Post-fix algorithm in java(这只是对待+ *,但修改非常简单)