Skip to content
July 18, 2011 / oop123

Writing a Simple Calculator in Java – Part 2

I started with a utility class with methods to get or set the string inside the display JTextField. Inside the setter, I limit the amount of digits the string can contains to 18 since that’s how much the text field can display without overflowing (accounting for a negative sign and decimal point).

package gui.action;
import javax.swing.JTextField;
import java.math.BigDecimal;

public class CalcUtils {
	//not for instantiation
	private CalcUtils() {}
	
	public static JTextField field = null;
	
	public static void setField(JTextField fie) {
		field = fie;
	}
	
	public static String getNum() {
		//not a number -> error
		try {
			new BigDecimal(field.getText());
			return field.getText();
		} catch(NumberFormatException e) {
			return "0";
		}
	}

	public static final int MAX_DIGITS = 18;
	
	public static void setNum(String str) {
		//set a limit of 18 digits for the str
		if (countDigits(str) <= MAX_DIGITS) field.setText(str);
		else field.setText("Error: number too big");
	}
	
	public static int countDigits(String str) {
		int count = 0;
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
				count++;
			}
		}
		return count;
	}
	
	//because i'm planning to work with BigDecimal
	public static String trimToMaxDigitsAndTrailing0IfNumIsFloat(String str) {
		if (!str.contains(".")) {
			return str;
		}

		//remove excess digits
		int count = 0;
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
				count++;
			}
			if (count == MAX_DIGITS) {
				str = str.substring(0, i + 1);
				break;
			}
		}
		
		//remove trailing 0
		count = 0;
		for (int i = str.length() - 1; i >= 0; i--) {
			char ch = str.charAt(i);
			if (ch == '0') {
				count++;
			} else if (ch == '.') {
				count++;
				break;
			} else {
				break;
			}
		}
		str = str.substring(0, str.length() - count);
		

		return str;
	}
}

I also added the following line to the MainFrame constructor for the utility class to work.

CalcUtils.setField(field.field);

Now let’s write some code so the number buttons actually do something (this can actually be written as an enum, but eh).

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

public class TypeNumber implements ActionListener {
	private String digit = null;

	//constructs with digit 0-9 repectively
	public TypeNumber(int num) {
		digit = String.valueOf(num);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String num = CalcUtils.getNum();

		//make sure "012" can't happen or user is inputing next number of expression
		if (num.equals("0") || newNum) {
			CalcUtils.setNum(digit);
			newNum = false;
		}
		//make sure there is less than 18 digits
		else if (CalcUtils.countDigits(num) < CalcUtils.MAX_DIGITS) {
			CalcUtils.setNum( num + digit);
		}
	}

	//Those will be used in +, -, *, /, = to control the typing of numbers
	private static boolean newNum = false;
	public static void startNewNum() {
		newNum = true;
	}
	public static boolean hasNewNum() {
		//opposite -> when the user type in a newNum, newNum becomes false, so we reverse the bool
		return !newNum;
	}
}

The class append the digit to the end of the display, unless it’s “0” or a new number need to be entered (i.e. user pressed +), in which case it would replace the number with the digit pressed. After some copy and paste to add the ActionListeners to the number buttons, they can actually type something now! 🙂

Screenshot of Java calculator with number punched in

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: