[英]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.