Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import jdk.swing.interop.SwingInterOpUtils;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.util.Arrays;
- import java.util.TreeMap;
- import java.util.Map;
- /**
- * A simple calculator program reading arithmetic expressions from the standard
- * input, evaluating them, and printing the results on the standard output.
- */
- public class Calc {
- private final int NO_OPERATORS = -1;
- /**
- * Evaluates an arithmetic expression. The grammar of accepted expressions
- * is the following:
- *
- * <code>
- * <p>
- * expr ::= factor | expr ('+' | '-') expr
- * factor ::= term | factor ('*' | '/') factor
- * term ::= '-' term | '(' expr ')' | number | id | function | binding
- * number ::= int | decimal
- * int ::= '0' | posint
- * posint ::= ('1' - '9') | posint ('0' - '9')
- * decimal ::= int '.' ('0' - '9') | '.' ('0' - '9')
- * id ::= ('a' - 'z' | 'A' - 'Z' | '_') | id ('a' - 'z' | 'A' - 'Z' | '_' | '0' - '9')
- * function ::= ('sqrt' | 'log' | 'sin' | 'cos') '(' expr ')'
- * binding ::= id '=' expr
- *
- * </code>
- * <p>
- * The binary operators are left-associative, with multiplication and division
- * taking precedence over addition and subtraction.
- * <p>
- * Functions are implemented in terms of the respective static methods of
- * the class java.lang.Math.
- * <p>
- * The bindings produced during the evaluation of the given expression
- * are stored in a map, where they remain available for the evaluation
- * of subsequent expressions.
- * <p>
- * Before leaving this method, the value of the given expression is bound
- * to the special variable named "_".
- *
- * @param expr well-formed arithmetic expression
- * @return the value of the given expression
- */
- public double eval(String expr) {
- bindings.put("pi", Math.PI);
- if (expr.contains("=")) {
- return storeValueInMap(expr);
- } else {
- int lastOperatorIndex = getLastOperatorIndex(expr);
- if (lastOperatorIndex == NO_OPERATORS) {
- return Double.parseDouble(expr);
- }
- String leftExpr, rightExpr;
- rightExpr = expr.substring(lastOperatorIndex + 1);
- leftExpr = expr.substring(0, lastOperatorIndex);
- System.out.println("Right Expression is " + rightExpr);
- System.out.println("Left Expression is " + leftExpr);
- switch (expr.charAt(lastOperatorIndex)) {
- case '+':
- System.out.println("PLUS");
- return eval(leftExpr) + eval(rightExpr);
- case '-':
- System.out.println("MINUS");
- return eval(leftExpr) - eval(rightExpr);
- case '*':
- System.out.println("KEFEL");
- return eval(leftExpr) * eval(rightExpr);
- case '/':
- System.out.println("HILUK");
- return eval(leftExpr) / eval(rightExpr);
- default:
- throw new IllegalStateException("Unexpected value: " + expr.charAt(lastOperatorIndex) + "/n you've entered an unsupported operator");
- }
- }
- }
- private int getLastOperatorIndex(String expr) {
- int operatorIndex = NO_OPERATORS;
- char operator;
- for (int i = 0; i < expr.length(); i++) {
- //check the operator
- operator = expr.charAt(i);
- if (expr.charAt(i) == '+' || expr.charAt(i) == '-') {
- operatorIndex = i;
- } else if (expr.charAt(i) == '*' || expr.charAt(i) == '/') {
- if(expr.contains("+") || expr.contains("-")) {
- }
- if (expr.charAt(operatorIndex) == '+' || expr.charAt(operatorIndex) == '-') {
- // continue loop
- } else if (expr.charAt(operatorIndex) == '*' || expr.charAt(operatorIndex) == '/') {
- for (int j = 0; j < expr.length(); j++) {
- if (expr.charAt(i) == '+' || expr.charAt(i) == '-') {
- operatorIndex = expr.charAt(i);
- }
- }
- }
- }
- }
- return operatorIndex;
- }
- // FUNCTION ZONE :
- private double storeValueInMap(String expr) {
- int indexOfEqv = expr.indexOf('=');
- int sizeIndex = expr.length();
- String rightSide, leftSide;
- rightSide = expr.substring(indexOfEqv + 1, sizeIndex);
- System.out.println(rightSide);
- double valueToStore = eval(rightSide);
- System.out.println(valueToStore);
- leftSide = expr.substring(0 , indexOfEqv);
- System.out.println("left side is = " + leftSide);
- bindings.put(leftSide, valueToStore); // כל מה שמצד שמאל להכניס לשם ומה שמימין להכניס לערך.
- return valueToStore;
- }
- // TODO: return the value of the given expression
- // some examples:
- // "1+2*3+4" returns 11.0
- // "(1+2)*(3+4)" returns 21.0
- // "sqrt(2)*sqrt(2) returns 2.0
- // "pi=3.14159265359" returns 3.14159265359
- // and binds the identifier 'pi' to the same value
- // "cos(pi)" should then return -1
- // throw new UnsupportedOperationException();
- // }
- public Map<String,Double> bindings() {
- return bindings;
- }
- private final Map<String,Double> bindings = new TreeMap<>();
- public static void main(String[] args) throws IOException {
- Calc calc = new Calc();
- try (BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
- PrintWriter out = new PrintWriter(System.out, true)) {
- while (true) {
- String line = in.readLine();
- if (line == null) {
- break;
- }
- line = line.trim();
- if (line.isEmpty()) {
- continue;
- }
- try {
- if (!line.startsWith(":")) {
- // handle expression
- out.println(calc.eval(line));
- } else {
- // handle command
- String[] command = line.split("\\s+", 2);
- switch (command[0]) {
- case ":vars":
- calc.bindings().forEach((name, value) ->
- out.println(name + " = " + value));
- break;
- case ":clear":
- if (command.length == 1) {
- // clear all
- calc.bindings().clear();
- } else {
- // clear requested
- calc.bindings().keySet().removeAll(Arrays.asList(command[1].split("\\s+")));
- }
- break;
- case ":exit":
- case ":quit":
- System.exit(0);
- break;
- default:
- throw new RuntimeException("unrecognized command: " + line);
- }
- }
- } catch (Exception ex) {
- System.err.println("*** ERROR: " + ex.getMessage());
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement