Java中的递归程序 [英] Recursive program in Java
问题描述
我有一个程序可以实现这一点:
I have a program that realizes this:
Input: "(-123)+(200)" -> String
Output: 77 -> Int
Input: "((-123)+(200))*((2)+(1))"
Output: 231
好吧,我有代码,但我不知道使用正则表达式是否是个好主意.老师给了我一个分隔String的函数,例如:
Well, I have the code, but I don't know if it's a good idea to use regular expressions. The teachers gave me a function that separates the String, for example:
int n = StringUtils.exprMainOperator ("(-123)+(200)");
n = 7;
我的想法是将每个字符串用 'n' 分隔在一个子字符串中,但我不知道如何递归地实现这一点.任何想法?请不要在代码中,所以我可以学习,谢谢.
My idea is to separate, by 'n' each String, in a substring, but I don't know how to realize this recursively. Any idea? Not in code please, so I can learn, thanks.
推荐答案
实现它的方法有很多种,这是一些可以工作的伪代码.我假设您只有算术运算符,并且 StringUtils.exprMainOperator
处理括号/操作优先级:
There are many ways of implementing it, this is some pseudocode that would work. I am assuming that you only have arithmetic operators, and that StringUtils.exprMainOperator
handles parenthesis/priority of operations:
public static int evaluateExpression(String exp) {
if(exp.charAt(0) == '(' && exp.charAt(exp.length()-1) == ')'
&& /*These two parenthesis correspond to each other*/) return evaluateExpression(exp.substring(1, exp.length()-1));
if(/*is Valid Number*/) return Integer.parseInt(exp);
int n = StringUtils.exprMainOperator(exp);
char op = exp.charAt(n);
String preop = exp.substring(0, n), postop = exp.substring(n+1);
if(op == '+') return evaluateExpression(preop) + evaluateExpression(postop);
if(op == '-') return evaluateExpression(preop) - evaluateExpression(postop);
if(op == '*') return evaluateExpression(preop) * evaluateExpression(postop);
if(op == '/') return evaluateExpression(preop) / evaluateExpression(postop);
//You shouldn't reach this part of the code
return -1;
}
这篇关于Java中的递归程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!