Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Split a Java Calculator into two seperate classes

Posted on 2011-02-13
5
Medium Priority
?
342 Views
Last Modified: 2012-05-11
hi, i've written the java calculator below as a single class but need to split it into two, one that contiains the gui and one that contains the calculator 'engine' - i'm new to swing and i'm not sure how to split them and get them to interact with one another.  any pointers please?

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;


/**
 * A Class that operates as both the framework for a calculator
 * and the calculator engine.
 *
 */
public class CalcFrame

{
   // private CalcEngine calc;

    private JFrame frame;
    private JTextField display;
    private JLabel status;

    //declare all buttons
    private JButton zeroButton = new JButton("0");
    private JButton oneButton = new JButton("1");
    private JButton twoButton = new JButton("2");
    private JButton threeButton = new JButton("3");
    private JButton fourButton = new JButton("4");
    private JButton fiveButton = new JButton("5");
    private JButton sixButton = new JButton("6");
    private JButton sevenButton = new JButton("7");
    private JButton eightButton = new JButton("8");
    private JButton nineButton = new JButton("9");
    private JButton plusButton = new JButton("+");
    private JButton minusButton = new JButton("-");
    private JButton divideButton = new JButton("/");
    private JButton multiplyButton = new JButton("*");
    private JButton equalsButton = new JButton("=");
    private JButton cancelButton = new JButton("C");


    private String lastNumberEntered;
    private String lastOperatorEntered;


    public CalcFrame()//CalcEngine engine)
    {

        //frame.setVisible(true);
       // calc = engine;
        makeFrame();
   
    /**
     * When an button is pressed perform that action
     */
   
   
        zeroButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("0");
            }
        });

        oneButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("1");
            }
        });


        twoButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("2");
            }
        });
       
        threeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("3");
            }
        });
       
        fourButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("4");
            }
        });
       
        fiveButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("5");
            }
        });
       
        sixButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("6");
            }
        });
       
        sevenButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("7");
            }
        });
       
        eightButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("8");
            }
        });
       
        nineButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("9");
            }
        });
        plusButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("+");
            }
        });
       
        minusButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("-");
            }
        });
       
        divideButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("/");
            }
        });
       
        multiplyButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("*");
            }
        });
       
        equalsButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                float calculation = performCalculation(lastNumberEntered, display.getText(),lastOperatorEntered);
                display.setText(calculation + "");
               
                //http://java.sun.com/docs/books/tutorial/java/data/converting.html
            }
        });

        cancelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                display.setText("");
                lastNumberEntered = null;
                lastOperatorEntered = null;
            }
        });

    }

    /**
     * This allows you to quit the calculator.
     */

    // Alows the class to quit.
    private void quit() {
        System.exit(0);


    }

    private void addToDisplay(String displayCharacter) {
        if (isAnOperator(displayCharacter)) {//if an operator is pressed, save the current number then display operator
            lastNumberEntered = display.getText();
            display.setText(displayCharacter);
            lastOperatorEntered = displayCharacter;
            //need to save what the display had here
        } else {
            if (isAnOperator(display.getText())) {//if display is an operator add a new number
                display.setText(displayCharacter);
            } else {
                display.setText(display.getText() + displayCharacter);//append displayCharacter to display
            }
        }
    }

    private float performCalculation(String firstNumberString, String secondNumberString, String operator) {
        //http://java.sun.com/docs/books/tutorial/java/data/converting.html
        float firstNumber = Float.valueOf(firstNumberString);
        float secondNumber = Float.valueOf(secondNumberString);
        if (operator.equals("+")) {
            return firstNumber + secondNumber;
        } else if (operator.equals("-")) {
            return firstNumber - secondNumber;
        } else if (operator.equals("*")) {
            return firstNumber * secondNumber;
        } else if (operator.equals("/")) {
            return firstNumber / secondNumber;
        } else {
            return -1;
        }
    }

    /**
     * Check if an input is an operator
     *
     * @return true if +,-,* or /
     */
    private boolean isAnOperator(String input) {
        if (input.equals("+") || input.equals("-") || input.equals("/") || input.equals("*")) {
            return true;
        }
        else return false;
    }

    // Calls the dialog frame with the information about the project.

    private void showAbout() {
        JOptionPane.showMessageDialog(frame,
                "Java Calculator Group Project 2011",
                "About Calculator Group Project",
                JOptionPane.INFORMATION_MESSAGE);
    }


   
    /**
     * The following creates a layout of the calculator frame.
     */
    private void makeFrame() {
        frame = new JFrame("Group Project Calculator");
        makeMenuBar(frame);

        JPanel contentPane = (JPanel) frame.getContentPane();
        contentPane.setLayout(new BorderLayout(8, 8));
        contentPane.setBorder(new EmptyBorder(10, 10, 10, 10));


        /**
         * Insert a text field
         */
        display = new JTextField("0");
        contentPane.add(display, BorderLayout.NORTH);

        //Container contentPane = frame.getContentPane();
        contentPane.setLayout(new GridLayout(4, 4));
        JPanel buttonPanel = new JPanel(new GridLayout(4, 4));
        contentPane.add(zeroButton);
        contentPane.add(oneButton);
        contentPane.add(twoButton);
        contentPane.add(threeButton);
        contentPane.add(fourButton);
        contentPane.add(fiveButton);
        contentPane.add(sixButton);
        contentPane.add(sevenButton);
        contentPane.add(eightButton);
        contentPane.add(nineButton);
        contentPane.add(plusButton);
        contentPane.add(minusButton);
        contentPane.add(divideButton);
        contentPane.add(multiplyButton);
        contentPane.add(equalsButton);
        contentPane.add(cancelButton);

        contentPane.add(buttonPanel, BorderLayout.CENTER);

       
        //contentPane.add(status, BorderLayout.SOUTH);

        frame.pack();
        frame.setVisible(true);
    }

    /**
     * Create the main frame's menu bar.
     * The frame that the menu bar should be added to.
     */
    private void makeMenuBar(JFrame frame) {
        final int SHORTCUT_MASK =
        Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();


        JMenuBar menubar = new JMenuBar();
        frame.setJMenuBar(menubar);

        JMenu menu;
        JMenuItem item;

        // create the File menu
        menu = new JMenu("File");
        menubar.add(menu);

        // create the Quit menu with a shortcut "Q" key.
        item = new JMenuItem("Quit");
        item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));
        item.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                quit();
            }
        });
       
        menu.add(item);

        // Adds an about menu.
        menu = new JMenu("About");
        menubar.add(menu);

        // Displays
        item = new JMenuItem("Calculator Project");
        item.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                showAbout();
            }
        });
        menu.add(item);

    }


    public static void main(String[] args) {
       
    }

}
0
Comment
Question by:t38
5 Comments
 
LVL 47

Assisted Solution

by:for_yan
for_yan earned 400 total points
ID: 34884440
One way of doing it is to create a separate class, say, Calculation,  which will
have members - first operand, second operand, operator.

It can have set methods which will set echa of the operands and operrator
and will have get Result method which would return the result.
When  a user enters number digits you can accumulate them
even in
the GUI class, but when userr enters operator sign you set the first operand
and operator. When the user then entrers equal sign - you
call get Result of that class
And then you implemnet getResult by analyzing the type of oeration
and performing calculation.
I guess ther are of course many ways,
but this would require  not that much typing.
Still I hope should fit your requirement.


 
0
 
LVL 7

Expert Comment

by:dimaj
ID: 34884573
Try looking at some patterns...

For a calculator you could consider an MVC pattern (http://en.wikipedia.org/wiki/Model%E2%80%93View%E2%80%93Controller).

Your View is the for you want users to manipulate
Your Model does all the calculations and creates events with results
Your Controller defines all your user interaction. I believe, you could combine Model and Controller into a single class and once your computations is complete, simply update your form with required information.

Hope this will get you started... If you have any problems, let me know and I'll try to find some examples of this pattern for you.
0
 
LVL 5

Accepted Solution

by:
aciuica earned 800 total points
ID: 34884753
I send you your calculator splited is some more clases - a Calculator class which use some some Operation interface implemetations (Plus, Minus, Divide, Multiply):
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.border.EmptyBorder;


/**
 * A Class that operates as both the framework for a calculator
 * and the calculator engine.
 *
 */
public class CalcFrame

{
   // private CalcEngine calc;

    private JFrame frame;
    private JTextField display;
    private JLabel status;

    //declare all buttons
    private JButton zeroButton = new JButton("0");
    private JButton oneButton = new JButton("1");
    private JButton twoButton = new JButton("2");
    private JButton threeButton = new JButton("3");
    private JButton fourButton = new JButton("4");
    private JButton fiveButton = new JButton("5");
    private JButton sixButton = new JButton("6");
    private JButton sevenButton = new JButton("7");
    private JButton eightButton = new JButton("8");
    private JButton nineButton = new JButton("9");
    private JButton plusButton = new JButton("+");
    private JButton minusButton = new JButton("-");
    private JButton divideButton = new JButton("/");
    private JButton multiplyButton = new JButton("*");
    private JButton equalsButton = new JButton("=");
    private JButton cancelButton = new JButton("C");


    private String lastNumberEntered;
    private String lastOperatorEntered;

    private Calculator calculator = new Calculator();

    public CalcFrame()//CalcEngine engine)
    {

        //frame.setVisible(true);
       // calc = engine;
        makeFrame();
   
    /**
     * When an button is pressed perform that action
     */
   
   
        zeroButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("0");
            }
        });

        oneButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("1");
            }
        });


        twoButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("2");
            }
        });
       
        threeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("3");
            }
        });
       
        fourButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("4");
            }
        });
       
        fiveButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("5");
            }
        });
       
        sixButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("6");
            }
        });
       
        sevenButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("7");
            }
        });
       
        eightButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("8");
            }
        });
       
        nineButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("9");
            }
        });
        plusButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("+");
            }
        });
       
        minusButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("-");
            }
        });
       
        divideButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("/");
            }
        });
       
        multiplyButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToDisplay("*");
            }
        });
       
        equalsButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                float calculation = performCalculation(lastNumberEntered, display.getText(),lastOperatorEntered);
                display.setText(calculation + "");
               
                //http://java.sun.com/docs/books/tutorial/java/data/converting.html
            }
        });

        cancelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                display.setText("");
                lastNumberEntered = null;
                lastOperatorEntered = null;
            }
        });

    }

    /**
     * This allows you to quit the calculator.
     */

    // Alows the class to quit.
    private void quit() {
        System.exit(0);


    }

    private void addToDisplay(String displayCharacter) {
        if (isAnOperator(displayCharacter)) {//if an operator is pressed, save the current number then display operator
            lastNumberEntered = display.getText();
            display.setText(displayCharacter);
            lastOperatorEntered = displayCharacter;
            //need to save what the display had here
        } else {
            if (isAnOperator(display.getText())) {//if display is an operator add a new number
                display.setText(displayCharacter);
            } else {
                display.setText(display.getText() + displayCharacter);//append displayCharacter to display
            }
        }
    }

    private float performCalculation(String firstNumberString, String secondNumberString, String operator) {
        //http://java.sun.com/docs/books/tutorial/java/data/converting.html
        float firstNumber = Float.valueOf(firstNumberString);
        float secondNumber = Float.valueOf(secondNumberString);
        return calculator.compute(firstNumber, secondNumber, operator);
    }

    /**
     * Check if an input is an operator
     *
     * @return true if +,-,* or /
     */
    private boolean isAnOperator(String input) {
    	return calculator.isAnOperator(input);
    }

    // Calls the dialog frame with the information about the project.

    private void showAbout() {
        JOptionPane.showMessageDialog(frame,
                "Java Calculator Group Project 2011",
                "About Calculator Group Project",
                JOptionPane.INFORMATION_MESSAGE);
    }


   
    /**
     * The following creates a layout of the calculator frame.
     */
    private void makeFrame() {
        frame = new JFrame("Group Project Calculator");
        makeMenuBar(frame);

        JPanel contentPane = (JPanel) frame.getContentPane();
        contentPane.setLayout(new BorderLayout(8, 8));
        contentPane.setBorder(new EmptyBorder(10, 10, 10, 10));


        /**
         * Insert a text field
         */
        display = new JTextField("0");
        contentPane.add(display, BorderLayout.NORTH);

        //Container contentPane = frame.getContentPane();
        contentPane.setLayout(new GridLayout(4, 4));
        JPanel buttonPanel = new JPanel(new GridLayout(4, 4));
        contentPane.add(zeroButton);
        contentPane.add(oneButton);
        contentPane.add(twoButton);
        contentPane.add(threeButton);
        contentPane.add(fourButton);
        contentPane.add(fiveButton);
        contentPane.add(sixButton);
        contentPane.add(sevenButton);
        contentPane.add(eightButton);
        contentPane.add(nineButton);
        contentPane.add(plusButton);
        contentPane.add(minusButton);
        contentPane.add(divideButton);
        contentPane.add(multiplyButton);
        contentPane.add(equalsButton);
        contentPane.add(cancelButton);

        contentPane.add(buttonPanel, BorderLayout.CENTER);

       
        //contentPane.add(status, BorderLayout.SOUTH);

        frame.pack();
        frame.setVisible(true);
    }

    /**
     * Create the main frame's menu bar.
     * The frame that the menu bar should be added to.
     */
    private void makeMenuBar(JFrame frame) {
        final int SHORTCUT_MASK =
        Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();


        JMenuBar menubar = new JMenuBar();
        frame.setJMenuBar(menubar);

        JMenu menu;
        JMenuItem item;

        // create the File menu
        menu = new JMenu("File");
        menubar.add(menu);

        // create the Quit menu with a shortcut "Q" key.
        item = new JMenuItem("Quit");
        item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));
        item.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                quit();
            }
        });
       
        menu.add(item);

        // Adds an about menu.
        menu = new JMenu("About");
        menubar.add(menu);

        // Displays
        item = new JMenuItem("Calculator Project");
        item.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                showAbout();
            }
        });
        menu.add(item);

    }


    public static void main(String[] args) {
    	new CalcFrame();
    }

}

class Calculator {
	private Map<String, Operation> operations = new HashMap<String, Operation>();
	
	public Calculator() {
		operations.put("+", new Plus());
		operations.put("-", new Minus());
		operations.put("/", new Divide());
		operations.put("*", new Multiply());
	}
	
	public boolean isAnOperator(String input) {
		return operations.containsKey(input);		
	}
	
	public float compute(float op1, float op2, String operator) {
		if (operations.containsKey(operator)) {
			return operations.get(operator).compute(op1, op2);
		} else {
			return -1;
		}
	}
}

interface Operation {
	public float compute(float op1, float op2);
}

class Plus implements Operation {

	@Override
	public float compute(float op1, float op2) {
		return op1 + op2;
	}
}

class Minus implements Operation {

	@Override
	public float compute(float op1, float op2) {
		return op1 - op2;
	}
}

class Divide implements Operation {

	@Override
	public float compute(float op1, float op2) {
		return op1 / op2;
	}
}

class Multiply implements Operation {

	@Override
	public float compute(float op1, float op2) {
		return op1 * op2;
	}
}

Open in new window

0
 

Assisted Solution

by:ajran
ajran earned 800 total points
ID: 34893121
0
 

Author Comment

by:t38
ID: 34910111
thanks, i'm going to work on this today and will report back.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Suggested Courses

972 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question