You are on page 1of 14

Individual Assignment

Task: Built a calculator that contains the following functions: Addition Subtraction Multiplication Division Percentage Square Root Backspace Clear
SOURCE CODE
import import import import java.awt.*; java.awt.event.*; javax.swing.*; javax.swing.event.*;

public class Calculator extends JFrame implements ActionListener{ //initializing the required constant final int MAX_INPUT_LENGTH = 15; final int INPUT_MODE = 0; final int RESULT_MODE = 1; final int ERROR_MODE = 2; //initialize the mode for result int displayMode = INPUT_MODE; boolean clearOnNextDigit= true, percent; double lastNumber=0; String lastOperator= "0"; // initializing the buttons and buttons name JButton[] numbers = new JButton[10]; JButton[] controllers = new JButton[8]; JButton[] equals = new JButton[1]; JButton[] editors = new JButton[2]; String[] "0"}; String[] String[] String[] numbers_name = {"1", "2", "3", "4", "5", "6", "7", "8", "9", controllers_name = {"+", "-", "*", "/","%","\u221A",".","+/-"}; equals_name = {"="}; editors_name = {"Backspace", "CE"};

//instantiate component for displaying result JLabel answer; JLabel empty; Font f13 = new Font("monospaced", 1, 18);

1|Page

public JPanel createContentPane (){ //instantiate the required panel for each button categories JPanel totalGUI = new JPanel(); JPanel numberGUI = new JPanel(); JPanel editorGUI = new JPanel(); JPanel operatorGUI = new JPanel(); JPanel calGUI = new JPanel(); JPanel answers_panel = new JPanel(); //initialize the value for the answer object answer = new JLabel("0"); Dimension d = answer.getPreferredSize(); answer.setPreferredSize(new Dimension(d.width+225,d.height+15)); answer.setHorizontalAlignment(JLabel.RIGHT); answer.setBackground(Color.WHITE); answer.setOpaque(true); answer.setFont(f13); answer.setBorder(BorderFactory.createLoweredBevelBorder()); answers_panel.add(answer); //create an empty panel to fill empty spaces in grid layout JPanel empty_panel = new JPanel(); empty = new JLabel(" "); empty_panel.add(empty); //call the method to create the button based on their categories JPanel numbers_panel = new JPanel(); panelMaker(numbers, numbers_name, numbers_panel, Color.blue); JPanel controllers_panel = new JPanel(); panelMaker(controllers, controllers_name, controllers_panel, Color.red); JPanel equals_panel = new JPanel(); panelMaker(equals, equals_name, equals_panel, Color.green); JPanel editors_panel = new JPanel(); panelMaker(editors, editors_name, editors_panel, Color.orange); //set the layout for the main panel totalGUI.setLayout(new BoxLayout(totalGUI, BoxLayout.PAGE_AXIS)); //set the layout for each calculator area numberGUI.setLayout(new FlowLayout(FlowLayout.CENTER)); operatorGUI.setLayout(new GridLayout(2,1)); editorGUI.setLayout(new FlowLayout(FlowLayout.CENTER)); //set the layout for the answer panel calGUI.setLayout(new GridLayout(1,1,2,2)); //set the layout for each buttons based on their categories numbers_panel.setLayout(new GridLayout(4,3,2,2)); controllers_panel.setLayout(new GridLayout(4,1,2,2)); equals_panel.setLayout(new FlowLayout(FlowLayout.RIGHT)); editors_panel.setLayout(new FlowLayout(FlowLayout.LEFT));

2|Page

//adding the component to each corresponding panel calGUI.add(answers_panel); editorGUI.add(editors_panel); editorGUI.add(empty_panel); editorGUI.add(equals_panel); numberGUI.add(numbers_panel); numberGUI.add(controllers_panel); //add the subpanel into the master panel totalGUI.add(calGUI); totalGUI.add(editorGUI); totalGUI.add(numberGUI); return totalGUI; } // Creates the buttons needed for each panel. private void panelMaker(JButton[] buttons, String[] strings, JPanel panel, Color colour) { for(int i = 0; i < buttons.length; i++) { //set button names buttons[i] = new JButton(strings[i]); //set butoon color buttons[i].setForeground(colour); //add button to the panel panel.add(buttons[i]); //add action listener to each button created buttons[i].addActionListener(this); } } public void actionPerformed(ActionEvent e){ double result = 0; // Search for the button pressed until end of array or key found for (int i=0; i<numbers.length; i++) { //check which button is pressed if(e.getSource() == numbers[i]) { //set action to be taken for each button switch(i) { case 0: //call the addDigitToDisplay method with the number intended to be added as parameters addDigitToDisplay(1); break; case 1: addDigitToDisplay(2);

3|Page

break; case 2: addDigitToDisplay(3); break; case 3: addDigitToDisplay(4); break; case 4: addDigitToDisplay(5); break; case 5: addDigitToDisplay(6); break; case 6: addDigitToDisplay(7); break; case 7: addDigitToDisplay(8); break; case 8: addDigitToDisplay(9); break; case 9: addDigitToDisplay(0); break; } } } for (int i=0; i<controllers.length; i++) { if(e.getSource() == controllers[i]) { switch(i) { case 0: //call the processOperator method with the operation as parameters processOperator("+"); break; case 1: processOperator("-"); break; case 2: processOperator("*"); break;

4|Page

case 3: processOperator("/"); break; case 4: //calculate the percentage for intended number if (displayMode != ERROR_MODE){ try { result = getNumberInDisplay() / 100; displayResult(result); } //catch error occured during calculation catch(Exception ex) { displayError("Invalid input for function!"); displayMode = ERROR_MODE; } } break; case 5: //calculate the square root for intended number if (displayMode != ERROR_MODE) { try { //check if the current number is negative if (getDisplayString().indexOf("-") == 0) displayError("Invalid input for function!"); result = Math.sqrt(getNumberInDisplay()); displayResult(result); } //catch error occured during calculation catch(Exception ex) { displayError("Invalid input for function!"); displayMode = ERROR_MODE; } } break; case 6: //call the addDecimalPoint method addDecimalPoint(); break; case 7: //call the processSignChange method processSignChange();

5|Page

break; } } } for (int i=0; i<editors.length; i++) { if(e.getSource() == editors[i]) { switch(i) { //delete the last inputted number case 0: if (displayMode != ERROR_MODE){ setDisplayString(getDisplayString().substring(0, getDisplayString().length() - 1)); if (getDisplayString().length() < 1) setDisplayString("0"); } break; case 1: //call the clearAll method clearAll(); break; } } } if(e.getSource()== equals[0]) { //call the processEquals method processEquals(); } } void setDisplayString(String s){ //mutator to change the value of answer Jlabel answer.setText(s); } String getDisplayString (){ //accessor to get the value of answer Jlabel return answer.getText(); } void addDigitToDisplay(int digit){ //append the inputted number to the last inputted number if (clearOnNextDigit) setDisplayString(""); String inputString = getDisplayString(); if (inputString.indexOf("0") == 0){

6|Page

inputString = inputString.substring(1); } if ((!inputString.equals("0") || digit > 0) inputString.length() < MAX_INPUT_LENGTH){ setDisplayString(inputString + digit); } displayMode = INPUT_MODE; clearOnNextDigit = false; } void addDecimalPoint(){ //put a decimal point to the current number displayMode = INPUT_MODE; if (clearOnNextDigit) setDisplayString(""); String inputString = getDisplayString(); // If the input string already contains a decimal point, don't // do anything to it. if (inputString.indexOf(".") < 0) setDisplayString(new String(inputString + ".")); } void processSignChange(){ //change the current displayed number to negative/positive if (displayMode == INPUT_MODE) { String input = getDisplayString(); if (input.length() > 0 && !input.equals("0")) { if (input.indexOf("-") == 0) setDisplayString(input.substring(1)); else setDisplayString("-" + input); } } else if (displayMode == RESULT_MODE) { double numberInDisplay = getNumberInDisplay(); if (numberInDisplay != 0) displayResult(-numberInDisplay); } } void clearAll() { //reset current calculation/operation setDisplayString("0"); lastOperator = "0"; &&

7|Page

lastNumber = 0; displayMode = INPUT_MODE; clearOnNextDigit = true; } double getNumberInDisplay() { //get number from Jlabel and convert it to double datatype String input = answer.getText(); return Double.parseDouble(input); } void processOperator(String op) { //perform check whether the operation is the first operation if (displayMode != ERROR_MODE) { double numberInDisplay = getNumberInDisplay(); if (!lastOperator.equals("0")) { try { double result = processLastOperator(); displayResult(result); lastNumber = result; } catch (DivideByZeroException e) { } } else { lastNumber = numberInDisplay; } clearOnNextDigit = true; lastOperator = op; } } void processEquals(){ //view the result for the calculation double result = 0; if (displayMode != ERROR_MODE){ try { result = processLastOperator(); displayResult(result); } catch (DivideByZeroException e) { displayError("Cannot divide by zero!"); } lastOperator = "0";

8|Page

} } double processLastOperator() throws DivideByZeroException { //perform calculation operation double result = 0; double numberInDisplay = getNumberInDisplay(); //perform division operation if (lastOperator.equals("/")) { if (numberInDisplay == 0) throw (new DivideByZeroException()); result = lastNumber / numberInDisplay; } //perform multiplication operation if (lastOperator.equals("*")) result = lastNumber * numberInDisplay; //perform substraction operation if (lastOperator.equals("-")) result = lastNumber - numberInDisplay; //perform addition operation if (lastOperator.equals("+")) result = lastNumber + numberInDisplay; return result; } void displayResult(double result){ //convert result to string and reset the calculator mode setDisplayString(Double.toString(result)); lastNumber = result; displayMode = RESULT_MODE; clearOnNextDigit = true; } void displayError(String errorMessage){ //set the result error message setDisplayString(errorMessage); lastNumber = 0; displayMode = ERROR_MODE; clearOnNextDigit = true; } class DivideByZeroException extends Exception{ //catch divide by zero during division operation public DivideByZeroException() { super(); } public DivideByZeroException(String s) { super(s);

9|Page

} } private static void createAndShowGUI() { //instantiate the calculator class Calculator cal = new Calculator(); //initialize the frame configuration cal.setContentPane(cal.createContentPane()); cal.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); cal.setTitle("Java Calculator"); cal.pack(); cal.setVisible(true); cal.setSize(250, 250); cal.setLocation(400, 250); cal.setVisible(true); //display the frame cal.setResizable(false); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }

10 | P a g e

Output : Figure 1.1 : Default display and layout for calculator

Instruction : Compile and run the code

Figure 1.2 : Inputting number to the labelarea

Instruction : Click the number displayed on the calculator pad

Example input: 525809884

Figure 1.3 : Deleting number in the label area

Instruction : Click the Backspace button

Example input: Click Backspace button three times

11 | P a g e

Figure 1.4 : Clearing number and operation in the label area

Instruction : Click the CE button

Example input: Click CE once

Figure 1.5 : Performing addition operation

Instruction : Click the first number, click + button, click the second number, click = button.

Example input: 4+6

Figure 1.6 : Performing addition operation

Instruction : Click the first number, click - button, click the second number, click = button.

Example input: 10 - 8

12 | P a g e

Figure 1.7 : Performing multiplication operation

Instruction : Click the first number, click * button, click the second number, click = button.

Example input: 9*5

Figure 1.8 : Performing division operation

Instruction : Click the first number, click / button, click the second number, click = button.

Example input: 6/2

Figure 1.9 : Performing percentage operation

Instruction : Click the first number, click % button

Example input: 58 %

13 | P a g e

Figure 1.10 : Performing square root operation

Instruction : Click the first number, click button

Example input: 4

14 | P a g e

You might also like