Advertisement
Guest User

Untitled

a guest
May 24th, 2019
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.15 KB | None | 0 0
  1. import jdk.swing.interop.SwingInterOpUtils;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.io.PrintWriter;
  7. import java.util.Arrays;
  8. import java.util.TreeMap;
  9. import java.util.Map;
  10.  
  11. /**
  12.  * A simple calculator program reading arithmetic expressions from the standard
  13.  * input, evaluating them, and printing the results on the standard output.
  14.  */
  15. public class Calc {
  16.     private final int NO_OPERATORS = -1;
  17.  
  18.     /**
  19.      * Evaluates an arithmetic expression. The grammar of accepted expressions
  20.      * is the following:
  21.      *
  22.      * <code>
  23.      * <p>
  24.      * expr ::= factor | expr ('+' | '-') expr
  25.      * factor ::= term | factor ('*' | '/') factor
  26.      * term ::= '-' term | '(' expr ')' | number | id | function | binding
  27.      * number ::= int | decimal
  28.      * int ::= '0' | posint
  29.      * posint ::= ('1' - '9') | posint ('0' - '9')
  30.      * decimal ::= int '.' ('0' - '9') | '.' ('0' - '9')
  31.      * id ::= ('a' - 'z' | 'A' - 'Z' | '_') | id ('a' - 'z' | 'A' - 'Z' | '_' | '0' - '9')
  32.      * function ::= ('sqrt' | 'log' | 'sin' | 'cos') '(' expr ')'
  33.      * binding ::= id '=' expr
  34.      *
  35.      * </code>
  36.      * <p>
  37.      * The binary operators are left-associative, with multiplication and division
  38.      * taking precedence over addition and subtraction.
  39.      * <p>
  40.      * Functions are implemented in terms of the respective static methods of
  41.      * the class java.lang.Math.
  42.      * <p>
  43.      * The bindings produced during the evaluation of the given expression
  44.      * are stored in a map, where they remain available for the evaluation
  45.      * of subsequent expressions.
  46.      * <p>
  47.      * Before leaving this method, the value of the given expression is bound
  48.      * to the special variable named "_".
  49.      *
  50.      * @param expr well-formed arithmetic expression
  51.      * @return the value of the given expression
  52.      */
  53.     public double eval(String expr) {
  54.         bindings.put("pi", Math.PI);
  55.  
  56.         if (expr.contains("=")) {
  57.             return storeValueInMap(expr);
  58.  
  59.         } else {
  60.             int lastOperatorIndex = getLastOperatorIndex(expr);
  61.  
  62.             if (lastOperatorIndex == NO_OPERATORS) {
  63.                 return Double.parseDouble(expr);
  64.             }
  65.  
  66.             String leftExpr, rightExpr;
  67.             rightExpr = expr.substring(lastOperatorIndex + 1);
  68.             leftExpr = expr.substring(0, lastOperatorIndex);
  69.             System.out.println("Right Expression is " + rightExpr);
  70.             System.out.println("Left Expression is " + leftExpr);
  71.  
  72.             switch (expr.charAt(lastOperatorIndex)) {
  73.                 case '+':
  74.                     System.out.println("PLUS");
  75.                     return eval(leftExpr) + eval(rightExpr);
  76.  
  77.                 case '-':
  78.                     System.out.println("MINUS");
  79.                     return eval(leftExpr) - eval(rightExpr);
  80.  
  81.                 case '*':
  82.                     System.out.println("KEFEL");
  83.                     return eval(leftExpr) * eval(rightExpr);
  84.  
  85.                 case '/':
  86.                     System.out.println("HILUK");
  87.                     return eval(leftExpr) / eval(rightExpr);
  88.  
  89.                 default:
  90.                     throw new IllegalStateException("Unexpected value: " + expr.charAt(lastOperatorIndex) + "/n you've entered an unsupported operator");
  91.  
  92.             }
  93.         }
  94.  
  95.     }
  96.  
  97.     private int getLastOperatorIndex(String expr) {
  98.         int operatorIndex = NO_OPERATORS;
  99.         char operator;
  100.         for (int i = 0; i < expr.length(); i++) {
  101.             //check the operator
  102.             operator = expr.charAt(i);
  103.  
  104.  
  105.             if (expr.charAt(i) == '+' || expr.charAt(i) == '-') {
  106.                 operatorIndex = i;
  107.  
  108.             } else if (expr.charAt(i) == '*' || expr.charAt(i) == '/') {
  109.                 if(expr.contains("+") || expr.contains("-")) {
  110.  
  111.                 }
  112.                 if (expr.charAt(operatorIndex) == '+' || expr.charAt(operatorIndex) == '-') {
  113.                     // continue loop
  114.  
  115.                 } else if (expr.charAt(operatorIndex) == '*' || expr.charAt(operatorIndex) == '/') {
  116.  
  117.                     for (int j = 0; j < expr.length(); j++) {
  118.                         if (expr.charAt(i) == '+' || expr.charAt(i) == '-') {
  119.                             operatorIndex = expr.charAt(i);
  120.  
  121.                         }
  122.  
  123.                     }
  124.                 }
  125.             }
  126.         }
  127.         return operatorIndex;
  128.     }
  129.     // FUNCTION ZONE :
  130.  
  131.     private double storeValueInMap(String expr) {
  132.         int indexOfEqv = expr.indexOf('=');
  133.         int sizeIndex = expr.length();
  134.         String rightSide, leftSide;
  135.  
  136.         rightSide = expr.substring(indexOfEqv + 1, sizeIndex);
  137.         System.out.println(rightSide);
  138.         double valueToStore = eval(rightSide);
  139.         System.out.println(valueToStore);
  140.         leftSide = expr.substring(0 , indexOfEqv);
  141.         System.out.println("left side is = " + leftSide);
  142.         bindings.put(leftSide, valueToStore); // כל מה שמצד שמאל להכניס לשם ומה שמימין להכניס לערך.
  143.  
  144.         return valueToStore;
  145.     }
  146.  
  147.  
  148.  
  149.  
  150.  
  151.     // TODO: return the value of the given expression
  152.     // some examples:
  153.     // "1+2*3+4" returns 11.0
  154.     // "(1+2)*(3+4)" returns 21.0
  155.     // "sqrt(2)*sqrt(2) returns 2.0
  156.     // "pi=3.14159265359" returns 3.14159265359
  157.     //     and binds the identifier 'pi' to the same value
  158.     // "cos(pi)" should then return -1
  159.  
  160. //      throw new UnsupportedOperationException();
  161. //  }
  162.  
  163.     public Map<String,Double> bindings() {
  164.         return bindings;
  165.     }
  166.  
  167.     private final Map<String,Double> bindings = new TreeMap<>();
  168.  
  169.     public static void main(String[] args) throws IOException {
  170.         Calc calc = new Calc();
  171.         try (BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  172.              PrintWriter out = new PrintWriter(System.out, true)) {
  173.             while (true) {
  174.                 String line = in.readLine();
  175.                 if (line == null) {
  176.                     break;
  177.                 }
  178.                 line = line.trim();
  179.                 if (line.isEmpty()) {
  180.                     continue;
  181.                 }
  182.                 try {
  183.                     if (!line.startsWith(":")) {
  184.                         // handle expression
  185.                         out.println(calc.eval(line));
  186.                     } else {
  187.                         // handle command
  188.                         String[] command = line.split("\\s+", 2);
  189.                         switch (command[0]) {
  190.                             case ":vars":
  191.                                 calc.bindings().forEach((name, value) ->
  192.                                         out.println(name + " = " + value));
  193.                                 break;
  194.                             case ":clear":
  195.                                 if (command.length == 1) {
  196.                                     // clear all
  197.                                     calc.bindings().clear();
  198.                                 } else {
  199.                                     // clear requested
  200.                                     calc.bindings().keySet().removeAll(Arrays.asList(command[1].split("\\s+")));
  201.                                 }
  202.                                 break;
  203.                             case ":exit":
  204.                             case ":quit":
  205.                                 System.exit(0);
  206.                                 break;
  207.                             default:
  208.                                 throw new RuntimeException("unrecognized command: " + line);
  209.                         }
  210.                     }
  211.                 } catch (Exception ex) {
  212.                     System.err.println("*** ERROR: " + ex.getMessage());
  213.                 }
  214.             }
  215.         }
  216.     }
  217. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement