【问题标题】:Add numbers in a string with recursion in Java with substring使用子字符串在Java中使用递归在字符串中添加数字
【发布时间】:2022-01-13 11:32:52
【问题描述】:

我正在尝试从字符串中添加一些数字 例如字符串是“5 + 3 +2”。这应该返回 10 这是我获取运算符号的代码是“+”

        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?

谢谢。

【问题讨论】:

  • 您需要将字符串拆分为一系列操作数和运算符,而不仅仅是一个。尝试寻找数学表达式解析的教程,网上应该有很多。
  • indexOf 有一个带有 beginIndex 的重载版本。在循环中使用它。
  • 首先,您的字符串方程中没有- 字符,因此opIndex 将是-1。等式的拆分需要多一点……稳健。你需要的是一个数学方程解析器。
  • 如果您需要递归地执行此操作,请先读取第一个操作数,然后再读取运算符,然后递归地处理剩余的字符串。
  • @f1sh 那是我卡住的部分。你能给我一些进一步的解释或例子吗?

标签: java recursion numbers substring indexof


【解决方案1】:

如果您使用事物列表递归地执行操作,请始终按照以下模式思考:

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

所以对于"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。如果你还想支持减法,它会变得更复杂,但你会弄明白的。

【讨论】:

  • 非常感谢。我现在可以理解这个概念了。
  • 递归一开始很难掌握。当你看到解决方案时,它似乎很清楚......随着时间的推移你会学习这个概念。如果您愿意,可以投票和/或接受此答案:)
【解决方案2】:

“RHS”字符串最终会变成 " 3 + 2"。你的工作不是获得 3。你的工作是递归:将该字符串提供给你自己的算法,相信它有效。

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

【讨论】:

    【解决方案3】:

    你可以使用split方法来拆分弹簧

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

    现在迭代数组,你可以

    【讨论】:

    • 对不起,我忘了说我不能使用循环。仅递归。
    猜你喜欢
    • 2015-09-28
    • 2021-12-11
    • 2021-12-10
    • 2014-05-16
    • 2012-04-01
    • 2020-02-17
    • 2015-03-07
    • 2020-02-22
    • 2014-06-07
    相关资源
    最近更新 更多