使用递归计算Java中具有两个数字的字符串表达式



字符串表达式中的正数与负数相乘时遇到问题。

如果我的表达式是-4*5,那么它返回-20,但如果我放4*-5,那么它会返回-5而不是-20。

我做了一些调试,发现我的子字符串只包含-5,但*运算符后面没有数字,所以它返回0.0

我想在执行表达式之前检查负号,并确定它是否为负数。然而,它并没有如预期的那样。

我能得到一些帮助吗?

if (expression.contains("-")) 
{
int indexOfExpression = expression.lastIndexOf('-');
String beforeMinus = expression.substring(indexOfExpression-1,indexOfExpression);
if(beforeMinus.equals("*") || beforeMinus.equals("/")) 
{
double afterMinus = Double.parseDouble(expression.substring(indexOfExpression,indexOfExpression+2));
return afterMinus;
}else {
double rhs = evaluate(expression.substring(indexOfExpression+1));
return evaluate(expression.substring(0, indexOfExpression)) - rhs;
}
} else if (expression.contains("*")) {
int indexOfExpression = expression.lastIndexOf("*");
Double rhs = evaluate(expression.substring(indexOfExpression + 1));;
return evaluate(expression.substring(0, indexOfExpression)) *rhs;
}

这就是我目前所拥有的,输出是-5而不是-20。

代码中有很多错误,所以我认为从如何做得更好的角度来回答比调试更有意义。我假设您要执行由四个运算符+-*/之一分隔的两个数字的二进制运算。主要的困难是作为运算符的-和作为负数符号的-之间的模糊性(在这种情况下,这更像是-1的乘法,而不是减法(。以下不是一个防弹算法,而是给你一个更结构化的解决问题的方法。

class Operator {
public String op;
public int index;
}
Operator findOperator(String expression) {
// Assumes that 'expression' is a simple expression of the form:
//      <number><op><number>
// Find all instances of '+', '-', '*', '/'.
// If '-' appears one or more times with another symbol, the other one is
// the operator. If more than one '-' appears, determine which is the
// operator based on position (e.g. can't be the operator at index zero).
return new Operator(...);
}
double calculate(String op, String lhs, String rhs) {
double left = Double.parseDouble(lhs);
double right = Double.parseDouble(rhs);
switch (op) {
case "+":
return left + right;
// etc.
}
}
double calculate(String expression) {
Operator operator = findOperator(expression);
return calculate(
operator.op,
expression.substring(0, operator.index),
expression.substring(operator.index + 1));
}

相关内容

最新更新