summaryrefslogtreecommitdiffstats
path: root/Master/Software Architektur/SWA_Prakt2/src/net/sven_eisenhauer/swa_prakt2/ExpressionIterator.java
diff options
context:
space:
mode:
Diffstat (limited to 'Master/Software Architektur/SWA_Prakt2/src/net/sven_eisenhauer/swa_prakt2/ExpressionIterator.java')
-rw-r--r--Master/Software Architektur/SWA_Prakt2/src/net/sven_eisenhauer/swa_prakt2/ExpressionIterator.java47
1 files changed, 47 insertions, 0 deletions
diff --git a/Master/Software Architektur/SWA_Prakt2/src/net/sven_eisenhauer/swa_prakt2/ExpressionIterator.java b/Master/Software Architektur/SWA_Prakt2/src/net/sven_eisenhauer/swa_prakt2/ExpressionIterator.java
new file mode 100644
index 0000000..0cdd7a8
--- /dev/null
+++ b/Master/Software Architektur/SWA_Prakt2/src/net/sven_eisenhauer/swa_prakt2/ExpressionIterator.java
@@ -0,0 +1,47 @@
+package net.sven_eisenhauer.swa_prakt1;
+
+public class ExpressionIterator implements ArithmeticIterator {
+ private ArithmeticExpression baseNode;
+
+ public ExpressionIterator(ArithmeticExpression baseNode) {
+ this.baseNode = baseNode;
+ }
+
+ public void print() {
+ if(baseNode instanceof ArithmeticVariable) {
+ System.out.print(((ArithmeticVariable) baseNode).getName());
+ } else {
+ ArithmeticOperation actOperation = (ArithmeticOperation) baseNode;
+ ArithmeticIterator leftIter = new ExpressionIterator(actOperation.getLeftOperand());
+ ArithmeticIterator rightIter = new ExpressionIterator(actOperation.getRightOperand());
+ System.out.print("(");
+ leftIter.print();
+ System.out.print(actOperation.getOperationSign());
+ rightIter.print();
+ System.out.print(")");
+ }
+ }
+
+ public Number evaluate() {
+ if(baseNode instanceof ArithmeticVariable) {
+ return ((ArithmeticVariable) baseNode).getValue();
+ } else {
+ ArithmeticOperation actOperation = (ArithmeticOperation) baseNode;
+ ArithmeticIterator leftIter = new ExpressionIterator(actOperation.getLeftOperand());
+ ArithmeticIterator rightIter = new ExpressionIterator(actOperation.getRightOperand());
+ Number leftVal = leftIter.evaluate();
+ Number rightVal = rightIter.evaluate();
+ if(actOperation instanceof ArithmeticAddition) {
+ return leftVal.doubleValue() + rightVal.doubleValue();
+ } else if(actOperation instanceof ArithmeticSubstraction) {
+ return leftVal.doubleValue() - rightVal.doubleValue();
+ } else if(actOperation instanceof ArithmeticDivision) {
+ return leftVal.doubleValue() / rightVal.doubleValue();
+ } else if(actOperation instanceof ArithmeticMultiplication) {
+ return leftVal.doubleValue() * rightVal.doubleValue();
+ } else {
+ return null;
+ }
+ }
+ }
+}