[英]Alternative way to replace Nested While Loop in Java
I tried to Evaluate Mathematical Expressions in Java with the following code:我尝试使用以下代码评估 Java 中的数学表达式:
public double applyOp(char op,double b,double a)
{
switch (op)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
}
return 0;
}
public boolean hasPrecedence(char op1,char op2)
{
return (op1 != '*' && op1 != '/') || (op2 != '+' && op2 != '-');
}
public double evaluate(String input) {
Stack<Double> values = new Stack<>();
Stack<Character> ops = new Stack<>();
int stringIndex = 0;
while (stringIndex < input.length())
{
StringBuilder multiDigitsNumber = new StringBuilder();
// If the input is number put to stack values
if (input.charAt(stringIndex) >= '0' && input.charAt(stringIndex) <= '9')
{
while (stringIndex < input.length() && input.charAt(stringIndex) >= '0' && input.charAt(stringIndex) <= '9')
{
multiDigitsNumber.append(input.charAt(stringIndex++));
}
values.push(Double.parseDouble(multiDigitsNumber.toString()));
}
// If the input is operator put to stack ops
else
{
while (!ops.empty() && hasPrecedence(input.charAt(stringIndex),ops.peek()))
{
values.push(applyOp(ops.pop(),values.pop(),values.pop()));
}
ops.push(input.charAt(stringIndex++));
}
}
// Execute remain operator in stack values
while (!ops.empty()) {
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
}
// The final number in stack value is result
return values.pop();
}
Input example:输入示例:
12+24*2-30/5.....
12+24*2-30/5.....
The code above works fine but I wonder are there any way to replace上面的代码工作正常,但我想知道有什么方法可以替换
while (stringIndex < input.length() && input.charAt(stringIndex) >= '0' && input.charAt(stringIndex) <= '9')
{
multiDigitsNumber.append(input.charAt(stringIndex++));
}
with something else so I don't have to use nested while loop in this situation.用其他东西,所以我不必在这种情况下使用嵌套的 while 循环。 The goal is to catch number in string until it reach an operator
目标是在字符串中捕获数字,直到它到达运算符
Thanks in advance提前致谢
You can use Regex like this.您可以像这样使用正则表达式。
if (input.charAt(stringIndex) >= '0' && input.charAt(stringIndex) <= '9')
{
String number = input.substring(stringIndex).replaceAll("^(\\d+).*", "$1");
values.push(Double.parseDouble(number));
stringIndex += number.length();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.