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
左右括号是否相等   true

另外在推荐一种利用String类里面的方法来替换计算公式中的%

方法链接

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值