我想用整数替换所有使用标准输入的“变量”。用整数替换所有变量
输入字符串:
“PQ + PQ + PQR + 4”
说,我输入1为pq
和3 pqr
。 我想什么是
“1 + 1 + 3 + 4”
我怎么能得到这个? 目前,我的代码也取代pqr
与1r
,这是不合法的。
// replaces all variables to integer or double
String evalVariables(String line) {
Pattern p = Pattern.compile("(?i)(?:^|\\s+)([a-z]+)");
Matcher m = p.matcher(line);
while (m.find()) {
String targetStr = m.group();
System.out.println("targetStr: " + targetStr);
System.out.println("Enter a integer or a double value for the variable ");
System.out.print("[" + targetStr + "]: ");
Scanner sc = new Scanner(System.in);
String newStr = sc.next();
line = line.replaceAll(targetStr, newStr);
System.out.println("After replacement: "+ line);
m = p.matcher(line);
}
return line;
}