Skip to content
July 24, 2011 / oop123

Writing a Simple Calculator in Java – Part 5

Let’s define an enum to hold the memory functions (M+, MR, and MC).

package gui.action;
import java.awt.event.*;
import java.math.BigDecimal;

public enum Memory implements ActionListener {
	;

	//store the BigDecimal
	private static BigDecimal num = null;

	/*
	 * Should override this in the enums
	 */
	@Override
	public void actionPerformed(ActionEvent e) {}
}

M+: Add the stored BigDecimal and the current BigDecimal.

M_PLUS {
	public void actionPerformed(ActionEvent e) {
		BigDecimal num2 = new BigDecimal(CalcUtils.getNum());
		if (num != null) num = num.add(num2);
		else num = num2;

		if (BigDecimal.ZERO.equals(num)) {
			num = null;
		}
	}
}

MR: Show the stored BigDecimal.

M_RECALL {
	public void actionPerformed(ActionEvent e) {
		if (num != null) CalcUtils.setNum(num.toString());
	}
}

MC: Clear the stored BigDecimal.

M_CLEAR {
	public void actionPerformed(ActionEvent e) {
		num = null;
	}
}

The only thing missing is an indicator to user there is a number in memory. I’m not going to add that now it’s part 5, but it’s pretty simple and you can imagine how it can be implemented.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: