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
	public void actionPerformed(ActionEvent e) {}

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

	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.

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

MC: Clear the stored BigDecimal.

	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.


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: