From c1a240e873cb0e434ea98506d2f33b4a571e354a Mon Sep 17 00:00:00 2001 From: Stefan Suhren Date: Tue, 6 Jan 2015 11:43:01 +0100 Subject: Assignment No.12 first complete implementation. --- src/de/fhswf/in/inf/java1/aufgabe12/UPN.java | 132 +++++++++++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 src/de/fhswf/in/inf/java1/aufgabe12/UPN.java (limited to 'src/de/fhswf/in/inf/java1/aufgabe12/UPN.java') diff --git a/src/de/fhswf/in/inf/java1/aufgabe12/UPN.java b/src/de/fhswf/in/inf/java1/aufgabe12/UPN.java new file mode 100644 index 0000000..815e937 --- /dev/null +++ b/src/de/fhswf/in/inf/java1/aufgabe12/UPN.java @@ -0,0 +1,132 @@ +/** + * + */ +package de.fhswf.in.inf.java1.aufgabe12; + +import java.util.HashMap; +import java.util.Map; +import java.util.Stack; + +/** + * A class that calculates in UPN. + * + * @author $Author: $ + * @version $Revision: $, $Date: $ UTC + */ +public class UPN +{ + + private Stack upnStack = new Stack<>(); + + private static Map operators = new HashMap<>(); + + static + { + operators.put("+", new Addition()); + operators.put("-", new Subtraction()); + operators.put("*", new Multiplication()); + operators.put("/", new Division()); + operators.put("%", new Modulo()); + } + + /** + * Empty constructor. + * + */ + public UPN() + { + } + + /** + * Reads a string and puts it on the UPN upnStack. + * + * @param upnString + * A space delimited string in UPN notation. + */ + public final void calculate(String upnString) + { + if (upnString == null) + { + throw new IllegalArgumentException("UpnString can't be null."); + } + if (upnString.isEmpty()) + { + throw new IllegalArgumentException("UpnString can't be empty."); + } + + for (String string : upnString.split("\\s+")) + { + if (!string.isEmpty()) + { + Operator operator = operators.get(string); + + if (operator == null) + { + try + { + operator = new UnaryTemplate(string); + } + catch (IllegalArgumentException e) + { + if (!(e.getCause() instanceof NoSuchMethodException)) + { + throw e; + } + } + if (operator == null) + { + try + { + operator = new BinaryTemplate(string); + } + catch (IllegalArgumentException e) + { + if (!(e.getCause() instanceof NoSuchMethodException)) + { + throw e; + } + } + + } + if (operator != null) + { + operators.put(string, operator); + operator.eval(upnStack); + } + else + { + try + { + upnStack.add(Double.valueOf(string)); + } + catch (NumberFormatException e) + { + throw new IllegalArgumentException("String: \"" + string + + "\" is not a valid" + + " operator nor a valid operand."); + } + } + } + else + { + operator.eval(upnStack); + } + } + } + } + + /** + * Get the result of a calculation done before. + * + * @return The top most value on the UPN stack. + */ + public final double getResult() + { + if (upnStack.empty()) + { + throw new IllegalArgumentException("UPN stack is empty."); + } + return upnStack.peek(); + } + +} -- cgit v1.2.3-70-g09d2