次方法是一个简单的string字符串转算数运算的方法
不支持带括号限定运算顺序的运算 如:1+1+(1*1)这样的不支持
仅支持1+1+1-1*1/1 这样不带括号的运算
下面是原码
public static Integer calcu(String s){ Integer count=0; String[] st=s.split("[+,[-]]"); Pattern p1 = Pattern.compile("[+,[-]]?"); Matcher m1 = p1.matcher(s); Listl1 = new ArrayList<>();//按顺序存放加减符号 while (m1.find()) { String v1=m1.group(); if (v1.replaceAll(" ", "").length()==0) { continue; } if (v1.contains("+")) { l1.add("+"); }else if(v1.contains("-")){ l1.add("-"); } } List l2 = new ArrayList<>();//按顺序存放乘除运算后待进行加减运算的数字 for (String s1 : st) { if (s1.contains("*")||s1.contains("/")) { Pattern p = Pattern.compile("[*,/]?"); Matcher m = p.matcher(s1); List l3 = new ArrayList<>();//存放运算符号 while (m.find()) { String v1=m.group(); if (v1.replaceAll(" ", "").length()==0) { continue; } if (v1.contains("*")) { l3.add("*"); }else if(v1.contains("/")){ l3.add("/"); } } String[] st1=s1.split("[*,/]"); Integer i1=Integer.parseInt(st1[0]); for (int i = 0; i < l3.size(); i++) { String v2 = l3.get(i); if (v2.contains("*")) { i1=i1*Integer.parseInt(st1[i+1]); }else if(v2.contains("/")){ i1=i1/Integer.parseInt(st1[i+1]); } l2.add(i1); } }else { l2.add(Integer.parseInt(s1)); } } count=l2.get(0); for (int i = 0; i < l1.size(); i++) { String v3 = l1.get(i); if (v3.contains("+")) { count = count+l2.get(i+1); }else if(v3.contains("-")){ count = count-l2.get(i+1); } } return count; }