1
0
Fork 0

Spreadsheet calculate/evaluateOperator methods implemented.

pull/1/head
selim 2023-12-26 04:13:44 +01:00
parent 10682d1d92
commit 197a39a16a
1 changed files with 45 additions and 8 deletions

View File

@ -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();