diff --git a/Axel/src/de/hs_mannheim/informatik/spreadsheet/Spreadsheet.java b/Axel/src/de/hs_mannheim/informatik/spreadsheet/Spreadsheet.java index 7edd11a..f7877d0 100644 --- a/Axel/src/de/hs_mannheim/informatik/spreadsheet/Spreadsheet.java +++ b/Axel/src/de/hs_mannheim/informatik/spreadsheet/Spreadsheet.java @@ -210,25 +210,62 @@ public class Spreadsheet { * @return The result calculated. */ private long calculate(String formula) throws ArithmeticException { - Matcher m = Pattern.compile("([A-Z][0-9]*)|[-\\+\\*/]|[0-9]*").matcher(formula); + Matcher m = Pattern.compile("([A-Z][0-9]*)|[-+*/]|[0-9]*").matcher(formula); long res = 0; + long currentOperand = 0; + String currentOperator = "+"; + boolean firstOperator = true; - // TODO implement - - // uncomment the following to see an example how the elements of a formula can be accessed - while (m.find()) { // m.find() must always be used before m.group() + while (m.find()) { String s = m.group(); - if (!s.isEmpty()) { - System.out.println(s); + + if (s.matches(("[0-9]+"))) + currentOperand = Long.parseLong(s); + else if ((s.matches("[A-Z][1-9]*") || s.matches("[A-Z][1-9]*+")) && get(s).isEmpty()) + currentOperand = 0; + else if ((s.matches("[A-Z][1-9]*") || s.matches("[A-Z][1-9]*+"))) { + currentOperand = Long.parseLong(get(s)); + } else { + if (!firstOperator) { + res = evaluateOperator(res, currentOperand, currentOperator); + } else { + res = currentOperand; + firstOperator = false; + } + currentOperator = s; } } + if (!firstOperator) { + res = evaluateOperator(res, currentOperand, currentOperator); + } else + res = currentOperand; + return res; } - // ----- + private long evaluateOperator(long res, long currentOperand, String currentOperator) { + switch (currentOperator) { + case "+": + res += currentOperand; + break; + case "-": + res -= currentOperand; + break; + case "*": + res *= currentOperand; + break; + case "/": + res /= currentOperand; + break; + default: + throw new IllegalArgumentException("Invalid operator: " + currentOperator); + } + return res; + } + ///--- public String toString() { StringBuilder sb = new StringBuilder();