Pastebin launched a little side project called HostCabi.net, check it out ;-)Pastebin is 300% more awesome when you are logged in. Sign Up, it's FREE!
Guest

Calculator

By: a guest on Jan 27th, 2013  |  syntax: Java  |  size: 1.98 KB  |  hits: 46  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. class Expr
  2. {
  3.   // Sum = product
  4.   //     = sum '+' product
  5.   //     = sum '-' product
  6.   public double sum(String args)
  7.   {
  8.     for(int i = args.length(); i > 0; i--)
  9.     {
  10.       if(args.substring(i - 1, i).equals("+"))
  11.       {
  12.         return sum(args.substring(0, i - 1)) + product(args.substring(i, args.length())) ;
  13.       }
  14.       if(args.substring(i - 1, i).equals("-"))
  15.       {
  16.         return sum(args.substring(0, i - 1)) - product(args.substring(i, args.length())) ;
  17.       }
  18.     }
  19.     return product(args) ;
  20.   }
  21.  
  22.   // product = power
  23.   //         = product '*' power
  24.   //         = product '/' power
  25.   //         = product '%' power
  26.   public double product(String args)
  27.   {
  28.     for(int i = args.length(); i > 0; i--)
  29.     {
  30.       if(args.substring(i - 1, i).equals("*"))
  31.       {
  32.         return product(args.substring(0, i - 1)) * power(args.substring(i, args.length())) ;
  33.       }
  34.       if(args.substring(i - 1, i).equals("/"))
  35.       {
  36.         return product(args.substring(0, i - 1)) / power(args.substring(i, args.length())) ;
  37.       }
  38.       if(args.substring(i - 1, i).equals("%"))
  39.       {
  40.         return product(args.substring(0, i - 1)) % power(args.substring(i, args.length())) ;
  41.       }
  42.     }
  43.     return power(args) ;
  44.   }
  45.  
  46.   // power = term
  47.   //       = power '^' term
  48.   public double power(String args)
  49.   {
  50.     for(int i = args.length(); i > 0; i--)
  51.     {
  52.       if(args.substring(i - 1, i).equals("^"))
  53.       {
  54.         return Math.pow(power(args.substring(0, i - 1)),
  55.              term(args.substring(i, args.length()))) ;
  56.       }
  57.     }
  58.     return term(args) ;
  59.   }
  60.  
  61.   // term = number
  62.   public double term(String arg)
  63.   {
  64.     return Double.valueOf(arg) ;
  65.   }
  66.  
  67.   public static void main(String [] args)
  68.   {
  69.     Expr E = new Expr() ;
  70.     String expr = "" ;
  71.     for(String arg : args)
  72.     {
  73.       expr += arg ;
  74.     }
  75.     String value = String.valueOf(E.sum(expr)) ;
  76.     System.out.println("Value of given expression is " + value) ;
  77.   }
  78. }