/** * */ 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(); } }