[英]Replace a positive or negative decimal or integer next to another in brackets
如何使用Java在方括号中的正负十进制或整数附近替换另一个?
我正在使用Java制作计算器,但是当使用以下格式的括号时,我发现很难处理它们:
(-x)(-y)
(x)(y)
正数或负数的其他组合仅在必须将我的代码不适用的没有乘法符号的方括号括起来时才起作用。 如果有使用Java regex的简单方法,那么我很乐意找到方法。 任何帮助是极大的赞赏! 这是到目前为止我处理括号的代码
setExpression(exp);
while(exp.contains("(") && exp.contains(")")){
int lastOpen = exp.lastIndexOf("(");
int nextClose = lastOpen + exp.substring(lastOpen+1).indexOf(")") + 1;
//first close bracket after the last open bracket
//treats the bracket as a separate expression and so checks it's validity
if(sameNoBrackets() != ""){
return sameNoBrackets();
}
setExpression(exp.substring(lastOpen+1, nextClose));
result = checkExpression();
if(!result.equals("")){
//if true then there is an error message so program stops there
return result;
}else{
String newText = calculateResult();
lastOpen = exp.lastIndexOf("(");
nextClose = lastOpen + exp.substring(lastOpen+1).indexOf(")") + 1;
String lastChar = "";
String nextChar = "";
if(lastOpen > 0){
lastChar = String.valueOf(exp.charAt(lastOpen-1));
}
if(nextClose + 2 <= exp.length()){
nextChar = String.valueOf(exp.charAt(nextClose+1));
}
if(lastChar != ""){
if(!"+-/*".contains(lastChar)){
newText = "*"+newText;
}
}
if(!"+-/*".contains(nextChar)){
newText = newText+"*";
}
exp = exp.replace(exp.substring(lastOpen, nextClose+1), newText);
//removes the bracket and replaces with the appropriate replacement text
}
}
setExpression(exp);
//checks the validty of the expression onces the brackets have been removed
result = checkExpression();
if (result == ""){
//calculates the answer if there is no error
result = calculateResult();
}
//returns either the answer or the error message that has been generated
return result;
看一下数据结构Stack,它使您能够以更可行的方式来分解术语,以便可以根据其优先级进行计算。 因此,乘法问题也可以得到更好的解决,因为您知道,必须在结束括号之后再加上一个运算符,否则运算符将达到默认乘法或期末。
这样,由于堆栈使您能够解析至少是实现计算器所必需的常规语言,因此还可以解析嵌套的术语和方括号。
解决括号问题的一种简单解决方法是,预处理术语字面量,并用)*(替换每次出现的)(右括号和开括号),这样解析器就不能处理)(条件。但是正如EJP和Miho已经说过,您的实现将不能处理所有输入变体。
问题实际上是您的整个技术是错误的。
您需要查找Dijkstra调车码算法或递归下降表达式解析。
您根本不必将其作为特殊情况来处理:它只是自然而然地脱离了正确的实现。
您需要扔掉它,然后重新开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.