Exemple #1
0
  public static void main(String[] args) {
    int result = 0;

    Calculator myCalc = new Calculator();

    try {
      if (args.length != 1) {
        throw new IllegalArgumentException("There must be exactly one argument! e.g. add(1, 2)");
      }

      if (!myCalc.checkBrackets(args[0])) {
        throw new IllegalArgumentException(
            "Brackets of the input expression \"" + args[0] + "\" do NOT match!");
      }

      /* Normalize the expression by removing all the whitespaces around
       * opening/closing brackets and the comma separator.
       * Any remaining whitespaces after the normalization will indicate
       * an invalid expression during evaluation later on.
       */

      /* Remove all white spaces before and after the opening and closing brackets
       */
      String expr_v1 = args[0].replaceAll("(.)(\\s+)([()])(\\s+)(.)", "$1$3$5");

      /* Remove all spaces before and after the separator ,
       */
      String expr_v2 = expr_v1.replaceAll("(.)(\\s*)([,])(\\s*)(.)", "$1$3$5");

      String expr_v3 = expr_v2.replaceAll("(.)([,])(\\s+)(.)", "$1$2$4");

      myCalc.logger.setLevel(DEBUG);

      result = myCalc.evaluateExpression(expr_v3);

      /* Print the result only if the expression is valid. Otherwise, an error
       * message has already been logged.
       */
      System.out.println(result);
    } catch (Exception e) {
      myCalc.logger.log(ERROR, e.toString());
      return;
    }
  }