Advertisement
Guest User

[Java] Expression Evaluation (With Parens)

a guest
Jun 20th, 2014
363
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 4.21 KB | None | 0 0
  1. import java.util.Stack;
  2. import java.util.Scanner;
  3.  
  4. /* * * * * * * * * * * * * * * * * * * * * * * * * *
  5.  *
  6.  * Description: Evaluation Expression (with parens)
  7.  * Author     : Marco 'RootkitNeo' C.
  8.  * License    : GNU/GPL V.3
  9.  * * * * * * * * * * * * * * * * * * * * * * * * * *
  10.  */
  11.  
  12.  
  13. class EvaluateExpression {
  14.  
  15.   private EvaluateExpression() {}
  16.  
  17.   // Verifica se il token passato e' un numero
  18.   // @return  true if it's a number; false otherwise
  19.   // (work with negative number)
  20.   // --------------------------------------------------------------------------------
  21.   private static boolean isNumeric(String str)
  22.   {
  23.     return str.matches("-?\\d+(\\.\\d+)?");
  24.   }
  25.   // --------------------------------------------------------------------------------
  26.  
  27.  
  28.   // Verifica la priorita' degli operatori
  29.   // @return  true if token1 has a higher priority than token2
  30.   // --------------------------------------------------------------------------------
  31.   private static boolean isHightPriority(String token1, String token2)
  32.   {
  33.     switch(token2)
  34.     {
  35.       case "^":
  36.         if(!token1.equals("^")) return true;
  37.         else return false;
  38.       case "*":
  39.       case "/":
  40.         if(token1.equals("+") || token1.equals("-")) return true;
  41.         else return false;
  42.       case "+":
  43.       case "-":
  44.         return false;
  45.     }
  46.    
  47.     return false;
  48.   }
  49.   // ---------------------------------------------------------------------------------
  50.  
  51.  
  52.   // Parsing Infix Expression
  53.   // @return Postfix Expression
  54.   // ---------------------------------------------------------------------------------
  55.   private static String evaluate(String exp)
  56.   {
  57.     Stack<String> stack = new Stack<String>();
  58.     StringBuilder sb = new StringBuilder();
  59.    
  60.     Scanner scanner = new Scanner(exp);
  61.     scanner.useDelimiter(" ");
  62.    
  63.     while(scanner.hasNext())
  64.     {
  65.       String token = scanner.next();
  66.      
  67.       if(isNumeric(token))
  68.       {
  69.         sb.append(token);
  70.         sb.append(" ");
  71.       }
  72.       else if(!token.equals("(") && !token.equals(")"))
  73.       {
  74.         if(!stack.isEmpty() && isHightPriority(token,stack.peek()))
  75.         {
  76.           sb.append(stack.pop());
  77.           sb.append(" ");
  78.         }
  79.         stack.push(token);
  80.       }
  81.       else if(token.equals("("))
  82.       {
  83.         stack.push(token);
  84.       }
  85.       else if(token.equals(")"))
  86.       {
  87.         String e;
  88.        
  89.         while(!(e = stack.pop()).equals("("))
  90.         {
  91.           sb.append(e);
  92.           sb.append(" ");
  93.         }
  94.       }
  95.     }
  96.    
  97.     while(!stack.isEmpty()) sb.append(stack.pop());
  98.    
  99.     return sb.toString().trim();
  100.   }
  101.   // -----------------------------------------------------------------------------------
  102.  
  103.  
  104.   // Parsing Postfix expression
  105.   // @return  number (result)
  106.   // -----------------------------------------------------------------------------------
  107.   public static double calculate(String exp)
  108.   {
  109.     Stack<Double> stack = new Stack<Double>();
  110.     Scanner scanner = new Scanner(evaluate(exp));
  111.     scanner.useDelimiter(" ");
  112.    
  113.     while(scanner.hasNext())
  114.     {
  115.       String item = scanner.next();
  116.        
  117.       switch(item)
  118.       {
  119.         case "*":
  120.           stack.push(stack.pop()*stack.pop());
  121.           break;
  122.         case "/":
  123.           stack.push(stack.pop()/stack.pop());
  124.           break;
  125.         case "+":
  126.           stack.push(stack.pop()+stack.pop());
  127.           break;
  128.         case "-":
  129.           stack.push(stack.pop()-stack.pop());
  130.           break;
  131.         case "^": // Non funziona proprio correttamente in alcuni casi, ma l'ho aggiunta comunque
  132.           double f = stack.pop();
  133.           double s = stack.pop();
  134.           stack.push(Math.pow(s,f));
  135.           break;
  136.         default:
  137.           stack.push(Double.parseDouble(item));
  138.       }
  139.     }
  140.    
  141.     return stack.pop();
  142.   }
  143.   // -------------------------------------------------------------------------------------
  144.  
  145.  
  146. }
  147.  
  148. class TestExp {
  149.   public static void main(String[] args) {
  150.     // This is the correct format of the input string
  151.     System.out.println(EvaluateExpression.calculate("( 1 + 3 * ( 4 ^ 2 ) + ( ( 2 + 3 + 5 ) * 2 + 2 * 4 ) * 2 ) ^ 2"));
  152.   }
  153. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement