Humboldt-Universität zu Berlin - Mathematisch-Naturwissenschaftliche Fakultät - Wissensmanagement in der Bioinformatik

Parser.java

text/x-java Parser.java — 2.3 KB

Dateiinhalt

/**
 * A class for parsing arithmetic expressions
 */
public class Parser {

  /**
   * An exception that is thrown if the to-be-parsed expression is not
   * well-formed.
   */
  public static class ExpressionNotWellFormedException extends Exception {
    public ExpressionNotWellFormedException() {
    }
  }

  /**
   * Parses a given String, determines whether it is a well-formed expression,
   * and computes the expression.
   * 
   * @param expression
   *          the expression that is to be evaluated
   * @return the result of the evaluation / computation
   * @throws ExpressionNotWellFormedException
   *           if the expression is not well-formed, an exception is thrown
   */
  public static int parse(String expression)
      throws ExpressionNotWellFormedException {
    // TODO Code hier einfügen

    return 0;
  }

  /**
   * test cases
   */
  public static void main(String[] args) {
    {
      wellFormedCheck("((8+7)*2)", 30);
      wellFormedCheck("(4-(7-1))", -2);
      wellFormedCheck("8", 8);
      wellFormedCheck("((1+1)*(2*2))", 8);

      notWellFormedCheck(")8+)1(())");
      notWellFormedCheck("(8+())");
      notWellFormedCheck("-1");
      notWellFormedCheck("(   5    -7)");
      notWellFormedCheck("108");
      notWellFormedCheck("(8)");
    }
  }

  private static void checkAndPrint(String message, boolean correct) {
    System.out.println((correct ? "PASS:" : "FAIL:") + " " + message);
    assert (correct);
  }

  private static void notWellFormedCheck(String expression) {
    try {
      int returned = parse(expression);
      checkAndPrint("nicht wohlgeformter Ausdruck " + expression
          + " ausgewertet zu " + returned, false);
    } catch (ExpressionNotWellFormedException e) {
      checkAndPrint("Ausdruck " + expression
          + " als nicht wohlgeformt erkannt.", true);
    }
  }

  private static void wellFormedCheck(String expression, int expected) {
    try {
      int returned = parse(expression);
      checkAndPrint("Ausdruck " + expression + " ausgewertet zu " + returned
          + " (erwartet: " + expected + ")", returned == expected);
    } catch (ExpressionNotWellFormedException e) {
      checkAndPrint("Ausdruck " + expression
          + " fälschlicherweise als nicht wohlgeformt eingeschätzt.", false);
    }
  }
}