java中计算逻辑%的处理

介绍

我这个方法是将%以及前面的数字替换为相应的 符合正常计算的数字（ 即: x% --> (x*0.01) 这里的x为任意组合）

public class Test01 {
public static void main(String[] args) {
String s = "1%+(2+3)%+100%+300/((2+(5+2))%+((1+5)+(2+3))%/100)+10%*5+((4+5)+5)%+(3+(2%+3)%)%+100%";
StringBuilder sb = new StringBuilder(s);
sb.insert(0, "+");
String searchFor = "%";
int index = 0;
while ((index = sb.indexOf(searchFor, index)) != -1) {
char[] chars = sb.toString().toCharArray();
if (chars[index - 1] == ')') {
sb.replace(index, index + 1, "*0.01");
index += 5;
} else {
for (int i = index; i >= 0; i--) {
if (chars[i] == '*' || chars[i] == '/' || chars[i] == '+' || chars[i] == '-') {
sb.insert(i + 1, "(");
sb.replace(index + 1, index + 2, "*0.01)");
i++;
index += 6;
break;
}
}
}
index += searchFor.length();
}
String substring = sb.substring(1, sb.length());

Test01 test01 = new Test01();
int countRight = test01.getCount("(", substring);
int countLeft = test01.getCount(")", substring);

System.out.println(substring);
System.out.println("左右括号是否相等   " + (countRight == countLeft));
}

// 统计一个字符在字符串中出现的数量
public int getCount(String serchFor, String str) {
int count = 0;
int index = 0;
while ((index = str.indexOf(serchFor, index)) != -1) {
count++;
index += serchFor.length();
}
return count;
}
}


结果


(100*0.01)+300/((2+(5+2))*0.01+((1+5)+(2+3))*0.01/100)+(10*0.01)*5+((4+5)+5)*0.01+(3+(2+3)*0.01)*0.01



08-27

11-24 3086
02-20 24
06-30 168
01-20 36万+
04-21 15万+
07-27 1159
12-29 72
11-03 290