在Java中,使用子字符串通过递归将数字添加到字符串中



我正试图从字符串中添加一些数字例如,字符串是";5+3+2";。这应该返回10这是我的代码,用于获取运算符的编号是"0"+">

int opIndex= expression.indexOf("+");
Double lhs = Double.parseDouble(expression.substring(0, opIndex));
Double rhs = Double.parseDouble(expression.substring(opIndex+1));

我得到的回报是lhs=5(这正是我想要的(rhs=返回字符串错误(3+2(;

我怎么能只得到数字3,然后在(5+3(或任何其他方法之后做+2?

谢谢。

如果你用一个事物列表递归地做事,请始终按照以下模式思考:

  • 处理列表的第一个元素
  • 使用递归调用处理列表的其余部分

因此,在"5 + 3 +2"的情况下,将5"+"分开,然后将其余部分("3+2"(再次传递给相同的方法。

在开始之前删除空格也要容易得多。

public static void main(String[] args) {
String input = "5 + 3 + 2";
//remove spaces:
input = input.replaceAll(" +", "");
int r = evaluate(input);
System.out.println(r);
}
private static int evaluate(String s) {
int operatorIndex = s.indexOf('+');
if(operatorIndex == -1) {
//no operator found, s is the last number
//this is the base case that "ends" the recursion
return Integer.parseInt(s);
}
else {
//this is left hand side:
int operand = Integer.parseInt(s.substring(0, operatorIndex));
//this performs the actual addition of lhs and whatever rhs might be (here's where recursion comes in)
return operand + evaluate(s.substring(operatorIndex+1));
}
}

此代码打印10。如果你也想支持substraction,它会变得更加复杂,但你会明白的。

;RHS";字符串最终变成类似" 3 + 2"的东西。你的工作是而不是获得3。你的工作是递归:把这个字符串交给你自己的算法,相信它是有效的。

递归就是这样工作的:你假设你的算法已经工作了,然后你写它,用额外的规则调用自己,你只能用"更简单"的情况调用自己(因为否则它永远不会结束(,,您编写代码来显式处理最简单的情况(在这种情况下,如果我只给您的方法一个数字,可能会这样。如果我给它"5",它需要返回5,而不是递归(。

您可以使用拆分方法拆分弹簧

String array[]=expression.split("+")

现在itrate the aray and you can

最新更新