Skip to content
July 21, 2011 / oop123

Writing a Simple Calculator in Java – Part 4

Let’s define an enum to hold the unary functions.

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

public enum Unary implements ActionListener {
	;

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

Decimal Point: If there isn’t already a decimal point on the displayed number, append a decimal point.

DOT {
	public void actionPerformed(ActionEvent e) {
		String str = CalcUtils.getNum();
		if (!str.contains(".")) CalcUtils.setNum(str + ".");
	}
}

Reverse Sign: If there is a negative sign at the beginning of the number, take it away; otherwise, add it.

REVERSE_SIGN {
	public void actionPerformed(ActionEvent e) {
		String str = CalcUtils.getNum();
		if (str.startsWith("-")) CalcUtils.setNum(str.substring(1));
		else CalcUtils.setNum("-" + str);
		//or CalcUtils.setNum(str.startsWith("-") ? str.substring(1) : "-" + str)
	}
}

Percentage Sign: Divide the current number by 100.

PERCENTAGE {
	public void actionPerformed(ActionEvent e) {
		BigDecimal num = new BigDecimal(CalcUtils.getNum());
		num = num.divide(new BigDecimal("100"));
		CalcUtils.setNum(CalcUtils.trimToMaxDigitsAndTrailing0IfNumIsFloat(num.toString()));
	}
}

Square Root: Square root current number (use Math.sqrt())

SQRT {
	public void actionPerformed(ActionEvent e) {
		Double num = Math.sqrt(Double.parseDouble(CalcUtils.getNum()));
		CalcUtils.setNum(CalcUtils.trimToMaxDigitsAndTrailing0IfNumIsFloat(num.toString()));
	}
}

Inverse: Take the inverse (1/x) of current number.

INVERSE {
	public void actionPerformed(ActionEvent e) {
		BigDecimal num = new BigDecimal(CalcUtils.getNum());
		num = BigDecimal.ONE.divide(num, 20, BigDecimal.ROUND_HALF_UP);
		CalcUtils.setNum(CalcUtils.trimToMaxDigitsAndTrailing0IfNumIsFloat(num.toString()));
	}
}

Backspace: Delete last digit of current number. Also watch out when the current number only has one single digit.

BACKSPACE {
	public void actionPerformed(ActionEvent e) {
		String num = CalcUtils.getNum();
		if (num.length() == 1 || (num.length() == 2 && num.startsWith("-"))) {
			CalcUtils.setNum("0");
		} else {
			CalcUtils.setNum(num.substring(0, num.length() - 1));
		}
	}
}

Clear: Change displayed number to 0 and clear Operation.lastOp and Operation.lastNum (a trivial method so not going to show it here).

CLEAR {
	public void actionPerformed(ActionEvent e) {
		CalcUtils.setNum("0");
		Operation.clear();
	}
}
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: