字符串是1a2a(3a4)然後我能夠提取(3a4)&計算它,讓'x'爲答案然後替換爲主1a2ax &按正常計算( (a - add,s - sub,m - mul,d - div)Java遞歸提取最內括號直到沒有更多括號
對於上面的等式,我做了這樣的工作(只適用於我有一組括號)
public class task2 {
private static double parseString(String str) {
// declaring the operators' counters
int a = 1;
int s = 1;
int m = 1;
int d = 1;
// splitting the string up into operands and operators
double[] operands = Arrays.stream(str.split("[asmd]")).mapToDouble(Double::parseDouble).toArray();
String[] operators = str.split("\\d+");
// the rest is pretty much self-explanatory
double total = operands[0];
for (int i = 1 ; i < operators.length ; i++) { // note that i starts at 1 because the first item in operators
switch (operators[i]) { // array is an empty string
case "a":
total = total * a + operands[i];
a++;
break;
case "s":
total = total * s - operands[i];
s++;
break;
case "d":
total = total * d/operands[i];
d++;
break;
case "m":
total = total * m * operands[i];
m++;
break;
}
}
return total;
}
public static void main(String[] args){
String x= "1a(2a6a16)a9s88s77m9d5";
System.out.print("Expression \""+x+"\" on solving gives answer as ");
//To extract String with Bracket
Matcher m = Pattern.compile("\\((.*?)\\)").matcher(x);
String y = null;
while(m.find()) {
y = m.group(1);
}
String z = Double.toString(task2.parseString(y));
int p = (int)Double.parseDouble(z);
String q = Integer.toString(p);
x = x.replaceAll("\\p{P}","");
x = x.replace(y,q);
// To call method to find value
System.out.println(task2.parseString(x));
}
}
但概率來當Ñ方程是
((1a3a(9s9s(10d200))S(10m100a(192s187))A10)d2d8)
,當我必須應用最內的括號的遞歸提取直到沒有更多的括號,這是我我正在掙扎着。
首先(10d200)萃取和計算的,讓答案是 「P」,該方程變爲((1a3a(9s9sP)S(10m100a(192s187))A10)d2d8)
其次(9s9sp)萃取並計算,讓答案是 「Q」,方程變爲((1a3aQs(10m100a(192s187))A10)d2d8)
三(192s187)萃取和計算的,讓答案是 「R」,方程變爲((1a3aQs(10m100aR )a10)d2d8)
(10m100aR)提取並計算出來,設答案爲「S」,方程變成((1a3aQsSa10)d2d8)
第五(Td2d8)表達式計算。
Plz,幫幫我吧。提前致謝。
爲什麼你不顯示你迄今爲止做了什麼? – kism3t
再次嗨。那麼到目前爲止你嘗試過了什麼?在另一個問題,你已經得到了代碼來評估你的表達式(https://stackoverflow.com/q/44213894/5710637) – fafl
你好@fafl,我編輯thw問題的代碼,當表達式有一組括號。 – mssach