Java中的递归程序
我有一个程序可以实现这一点:Java中的递归程序,java,string,recursion,Java,String,Recursion,我有一个程序可以实现这一点: Input: "(-123)+(200)" -> String Output: 77 -> Int Input: "((-123)+(200))*((2)+(1))" Output: 231 我有代码,但我不知道使用正则表达式是否是个好主意。老师给了我一个分隔字符串的函数,例如: int n = StringUtils.exprMainOperator ("(-123)+(200)"); n = 7; 我的想法是,在一个子串中,用“n”分隔每个字符
Input: "(-123)+(200)" -> String
Output: 77 -> Int
Input: "((-123)+(200))*((2)+(1))"
Output: 231
我有代码,但我不知道使用正则表达式是否是个好主意。老师给了我一个分隔字符串的函数,例如:
int n = StringUtils.exprMainOperator ("(-123)+(200)");
n = 7;
我的想法是,在一个子串中,用“n”分隔每个字符串,但我不知道如何递归地实现这一点。有什么想法吗?请不要用代码,这样我可以学习,谢谢
//Here are the imports you need
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public static void main (String args [])
{
Scanner in = new Scanner (System.in);
in = /*your input*/;
System.out.println(StringEngineCalc(in));
}
public static String StringEngineCalc(String yourString) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
String calc= "";
try {
calc = engine.eval(message).toString();
} catch (ScriptException e) {
System.out.println("Error al realizar el cálculo.");
}
return calc;
}
在这里,您是一个使用calc返回字符串的类(如果您想要字符串,如果不只是删除“toString”并将public static字符串更改为public static int)
它使用javascript来解决数学问题,这是制作计算器最简单的方法:)实现它的方法很多,这是一些可以工作的伪代码。我假设您只有算术运算符,
StringUtils.exprMainOperator
处理括号/操作优先级:
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;
}
如果没有像“123”返回string.length()那样的运算符,StringUtils.exprMainOperator返回什么;在本例中为3;
StringUtils.exprMainOperator
是否考虑了括号和操作优先级?是的,例如,此字符串int n=StringUtils…(-123)+(200))*((2)+(2));n=14,此方法在等效括号中分隔表达式。我有一个问题,我有一个错误:missin return station,但我不知道我有return…?必须在方法末尾添加return
语句,因为编译器看到所有return
语句都在if
语句中。