我试图解决简单的字符串表达式,例如1 + 2 * 3/4,无支架。我完成了简单的整数部分,上面的表达式将完美地工作,但现在我已经卡住了十进制值,例如1.1 / 2.2 * 4.4我想要的是将整个十进制数推入堆栈(双倍),我已经工作了很长一段时间,但还是没有得到它,你的帮助将非常感激。目前的代码是:
import java.util.Stack;
import java.text.DecimalFormat;
public class EvaluateString
{
public static double evaluate(String expression)
{
char[] tokens = expression.toCharArray();
DecimalFormat df = new DecimalFormat("#.##");
// Stack for numbers: 'values'
Stack<Double> values = new Stack<Double>();
// Stack for Operators: 'ops'
Stack<Character> ops = new Stack<Character>();
for (int i = 0; i < tokens.length; i++)
{
// Current token is a whitespace, skip it
if (tokens[i] == ' ')
continue;
// Current token is a number, push it to stack for numbers
if (tokens[i] >= '0' && tokens[i] <= '9')
{
StringBuffer sbuf = new StringBuffer();
// There may be more than one digits in number
while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9')
sbuf.append(tokens[i++]);
values.push(Double.parseDouble(sbuf.toString()));
}
// Current token is an operator.
else if (tokens[i] == '+' || tokens[i] == '-' ||
tokens[i] == '*' || tokens[i] == '/')
{
// While top of 'ops' has same or greater precedence to current
// token, which is an operator. Apply operator on top of 'ops'
// to top two elements in values stack
while (!ops.empty() && hasPrecedence(tokens[i], ops.peek()))
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
// Push current token to 'ops'.
ops.push(tokens[i]);
}
}
// Entire expression has been parsed at this point, apply remaining
// ops to remaining values
while (!ops.empty())
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
// Top of 'values' contains result, return it
return Double.parseDouble(df.format(Double.parseDouble(String.valueOf(values.pop()))));
}
// Returns true if 'op2' has higher or same precedence as 'op1',
// otherwise returns false.
public static boolean hasPrecedence(char op1, char op2)
{
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
return false;
else
return true;
}
// A utility method to apply an operator 'op' on operands 'a'
// and 'b'. Return the result.
public static double applyOp(char op, double b, double a)
{
switch (op)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0)
throw new
UnsupportedOperationException("Cannot divide by zero");
return a / b;
}
return 0;
}
}
在价值被推入“价值”的部分中会有一些变化。叠加。
答案 0 :(得分:5)
为什么要自己编写代码?有很多第三种替代品:
答案 1 :(得分:1)
你做完了!只是变化不大:
while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9')
需要替换为
while (i < tokens.length && (Character.isDigit(tokens[i]) || tokens[i] == '.'))