mramine364

smart calc en java

Feb 20th, 2016
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.73 KB | None | 0 0
  1. /**
  2.  *
  3.  * @author amine_err
  4.  */
  5. public class Calc {
  6.    
  7.     public static boolean isNumber(String str){        
  8.         return str.matches("-?(\\d+|\\d+\\.\\d+|\\.\\d+|\\d+\\.)");
  9.     }
  10.    
  11.     public static double pow(double a, int b){
  12.         double res = 1;
  13.         int i = 0;
  14.         while( i<b ){
  15.             res *= a;
  16.             i++;
  17.         }
  18.         return res;
  19.     }
  20.    
  21.     public static double round(double n, int a){
  22.         double p = pow(10, a);
  23.         return Math.round(p*n)/p;
  24.     }
  25.    
  26.     public static boolean check(String exp) throws Exception {
  27.         //if syntax correct
  28.         // not empty
  29.         if ("".equals(exp)) {
  30.             throw new Exception("empty! ");
  31.         }
  32.         // no 2 [*,.,|] in a row
  33.         String ops[] = new String[]{"+", "-", "*", "/", "%", "^"};
  34.         for (String op : ops) {
  35.             for (String op1 : ops) {
  36.                 if (exp.contains(op + op1)) {
  37.                     //throw ;
  38.                     throw new Exception("syntax error! " + op + op1);
  39.                 }
  40.             }
  41.         }
  42.         // no op)
  43.         for (String op : ops) {
  44.             if (exp.contains(op + ")")) {
  45.                 throw new Exception("syntax error! " + op + ")");
  46.             }
  47.         }
  48.         // no (["*", "/", "%", "^"]
  49.         for (int i = 2; i < ops.length; i++) {
  50.             if (exp.contains("(" + ops[i])) {
  51.                 throw new Exception("syntax error! " + "(" + ops[i]);
  52.             }
  53.         }
  54.         // no start with ["*", "/", "%", "^"]
  55.         for (int i = 2; i < ops.length; i++) {
  56.             if (exp.charAt(0) == ops[i].charAt(0)) {
  57.                 throw new Exception("syntax error! starting with " + ops[i] );
  58.             }
  59.         }
  60.         //
  61.         int k = 0;
  62.         for (int i = 0; i < exp.length(); i++) {
  63.             if (exp.charAt(i) == '(') {
  64.                 k++;
  65.             }
  66.             if (exp.charAt(i) == ')') {
  67.                 k--;
  68.             }
  69.             if (k < 0) {
  70.                 throw new Exception("syntax error! mismatched parentheses ");
  71.             }
  72.         }
  73.         if (k > 0) {
  74.             throw new Exception("syntax error! mismatched parentheses ");
  75.         }
  76.         return true;
  77.     }
  78.    
  79.     public static double calc(String str) throws Exception{
  80.         // if str is a simple number
  81.         if ( isNumber(str) ) {
  82.             return Double.parseDouble(str);
  83.         }
  84.         else if (!str.equals("")) {
  85.             // (----) => ----
  86.             if (str.charAt(0) == '(' && str.charAt(str.length() - 1) == ')') {
  87.                 return calc(str.substring(1, str.length() - 1));
  88.             }
  89.             int k, i;
  90.             // +, -
  91.             for (i = str.length() - 1; i > -1; i--) {
  92.                 if (str.charAt(i) == ')') {
  93.                     k = -1;
  94.                     while (!(k == 0 && str.charAt(i) == '(')) {
  95.                         i--;
  96.                         if (str.charAt(i) == ')')
  97.                             k--;
  98.                         else if (str.charAt(i) == '(')
  99.                             k++;
  100.                     }
  101.                     i--;
  102.                 }
  103.                 if (i > -1) {
  104.                     if (str.charAt(i) == '+') {
  105.                         return calc(str.substring(0, i))+calc(str.substring(i + 1, str.length()));
  106.                     }
  107.                     if (str.charAt(i) == '-') {
  108.                         return calc(str.substring(0, i))-calc(str.substring(i + 1, str.length()));
  109.                     }
  110.                 }
  111.             }
  112.             // *, /, %
  113.             for (i = str.length() - 1; i > -1; i--) {
  114.                 if (str.charAt(i) == ')') {
  115.                     k = -1;
  116.                     while (!(k == 0 && str.charAt(i) == '(')) {
  117.                         i--;
  118.                         if (str.charAt(i) == ')')
  119.                             k--;
  120.                         else if (str.charAt(i) == '(')
  121.                             k++;
  122.                     }
  123.                     i--;
  124.                 }
  125.                 if (i > -1) {
  126.                     if (str.charAt(i) == '*') {
  127.                         return calc(str.substring(0, i))*calc(str.substring(i + 1, str.length()));
  128.                     }
  129.                     if (str.charAt(i) == '/') {
  130.                         return calc(str.substring(0, i))/calc(str.substring(i + 1, str.length()));
  131.                     }
  132.                     if (str.charAt(i) == '%') {
  133.                         return calc(str.substring(0, i))%calc(str.substring(i + 1, str.length()));
  134.                     }
  135.                 }
  136.             }            
  137.             for (i = 0; i < str.length(); i++) {
  138.                 if (str.charAt(i) == '(') {
  139.                     k = 1;
  140.                     while (!(k == 0 && str.charAt(i) == ')')) {
  141.                         i++;
  142.                         if (str.charAt(i) == ')')
  143.                             k--;
  144.                         else if (str.charAt(i) == '(')
  145.                             k++;
  146.                     }
  147.                     i++;
  148.                 }
  149.                 if (i < str.length()) {
  150.                     if (str.charAt(i) == '^') {
  151.                         return pow(calc(str.substring(0, i)),(int)calc(str.substring(i + 1, str.length())));
  152.                     }
  153.                 }
  154.             }
  155.             // look if there is a function
  156.             int fi = str.indexOf("(", 1);
  157.             if( fi!=-1 ){
  158.                 String function_name = str.substring(0,fi);
  159.                 int epi = str.length()-1;
  160.                 String parameter = str.substring(fi+1,epi);
  161.                 switch (function_name) {
  162.                     case "cos":
  163.                         return Math.cos( calc(parameter+"/180*"+Math.PI) );
  164.                     case "sin":
  165.                         return Math.sin( calc(parameter+"/180*"+Math.PI) );
  166.                     case "tan":
  167.                         return Math.tan( calc(parameter+"/180*"+Math.PI) );                
  168.                     default:
  169.                         throw new Exception(function_name+": is not defined");
  170.                 }
  171.             }            
  172.         }
  173.         return 0;
  174.     }
  175.    
  176.     public static void resultat(String expr){  
  177.         expr = expr.replaceAll(" ", "");
  178.         try {
  179.             if( check(expr) )
  180.                 System.out.println(round(calc(expr), 15));
  181.         } catch (Exception ex) {
  182.             System.out.println(ex.getMessage());
  183.         }
  184.     }
  185.  
  186.     public static void main(String[] args) {        
  187.         String expr = "1+2*2 +6*(1.2 -0.2)/3 +  cos(90)";
  188.         resultat(expr);
  189.        
  190.         String expr1 = "5+2*10+ccos(60)";
  191.         resultat(expr1);
  192.        
  193.         String expr2 = "(10*5+10)^2/100";
  194.         resultat(expr2);        
  195.     }  
  196. }
Advertisement
Add Comment
Please, Sign In to add comment