package calculator; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigInteger; import java.util.ArrayList; public class CalcModel { private ArrayList log; private BigInteger calcValue; /** * Creates a model with no user values and a calculated * value of zero. * */ public CalcModel() { this.log = new ArrayList(); this.clear(); } public void open(File file) { FileInputStream f = null; ObjectInputStream in = null; ArrayList log = null; try { f = new FileInputStream(file); in = new ObjectInputStream(f); log = (ArrayList) in.readObject(); in.close(); this.log = log; final int last = this.log.size() - 1; this.calcValue = new BigInteger(this.log.get(last)); System.out.println(log); } catch(IOException ex) {} catch(ClassNotFoundException ex) {} } public void save(File file) { FileOutputStream f = null; ObjectOutputStream out = null; try { f = new FileOutputStream(file); out = new ObjectOutputStream(f); out.writeObject(this.log); out.close(); } catch(IOException ex) {} System.out.println(log); } /** * Clears the user values and the calculated value. */ public void clear() { this.log.clear(); this.calcValue = BigInteger.ZERO; this.log.add(this.calcValue.toString()); } /** * Adds the calculated value by a user value. * * @param userValue * The value to add to the current calculated value by. */ public void sum(BigInteger userValue) { this.calcValue = this.calcValue.add(userValue); this.updateLog("+", userValue.toString()); } /** * Subtracts the calculated value by a user value. * * @param userValue * The value to subtract from the current calculated value by. */ public void subtract(BigInteger userValue) { this.calcValue = this.calcValue.subtract(userValue); this.updateLog("-", userValue.toString()); } /** * Multiplies the calculated value by a user value. * * @param userValue * The value to multiply the current calculated value by. */ public void multiply(BigInteger userValue) { this.calcValue = this.calcValue.multiply(userValue); this.updateLog("*", userValue.toString()); } /** * Divides the calculated value by a user value. * * @param userValue * The value to multiply the current calculated value by. * @pre. userValue is not equivalent to zero. */ public void divide(BigInteger userValue) { this.calcValue = this.calcValue.divide(userValue); this.updateLog("/", userValue.toString()); } private void updateLog(String operation, String value) { this.log.add(operation); this.log.add(value); this.log.add("="); this.log.add(this.calcValue.toString()); } /** * Get the current calculated value. * * @return The current calculated value. */ public BigInteger getCalcValue() { return this.calcValue; } public BigInteger getLastUserValue() { if(this.log.size() == 1) { return BigInteger.ZERO; } final int last = this.log.size() - 1; return new BigInteger(this.log.get(last - 2)); } }