# String Calculator

May 9th, 2021
549
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. private static Pattern extra = Pattern.compile("((^[-])?[0-9.]+)([*/])(-?[0-9.]+)"),
2.         superr = Pattern.compile("\\(.*?\\)+"),
3.         normal = Pattern.compile("((^[-])?[0-9.]+)([+-])(-?[0-9.]+)");
4.
5. public static double calculate(String val) {
6.     if(val.contains("(")&&val.contains(")")) {
7.         Matcher s = superr.matcher(val);
8.         while(s.find()) {
9.             val=val.replace(s.group(), calculate(s.group().substring(1, s.group().length()-1))+"");
10.             s = superr.matcher(val);
11.         }
12.     }
13.     if(val.contains("*")||val.contains("/")) {
14.         Matcher s = extra.matcher(val);
15.         while(s.find()) {
16.             double a = getDouble(s.group(1));
17.             String b = s.group(3);
18.             double d = getDouble(s.group(4));
19.             val=val.replace(s.group(), (b.equals("*")?a*d:a/d)+"");
20.             s = extra.matcher(val);
21.         }
22.     }
23.     if(val.contains("+")||val.contains("-")) {
24.         Matcher s = normal.matcher(val);
25.         while(s.find()) {
26.             double a = getDouble(s.group(1));
27.             String b = s.group(3);
28.             double d = getDouble(s.group(4));
29.             val=val.replace(s.group(), (b.equals("+")?a+d:a-d)+"");
30.             s = normal.matcher(val);
31.         }
32.     }
33.     return getDouble(val.replaceAll("[^0-9+.-]", ""));
34. }
35.
36. private static double getDouble(String a) {
37.     try {
38.         return Double.parseDouble(a);
39.     }catch(Exception er) {
40.         try {
41.             return Long.parseLong(a);
42.         }catch(Exception err) {
43.             return 0;
44.         }
45.     }
46. }
RAW Paste Data