Write a simple calculator program which allows the user to enter two decimal numbers, and compute their sum, difference, product or quotient.

You should have two JTextField components that allow the user to input two numbers (treat them as floats), and four JButton components which are labelled x, +,/,-. The result of the calculation is displayed using a JLabel.

Part 1

Create the application framework, and add all the components. Look at the Greeter application from the Week 19 Lecture as an example. You will need to derive a class from JPanel, and add two JTextField components, four JButton components and a JLabel for the result. You can add the action Performed method, but for now it should be an empty method. see image.

When this stage is complete, you should have a window that looks like the picture above. You should be able to type text into the text fields, and press the buttons, but the inputs will have no effect.

Part 2

Now add the functionality. You will need to respond to a button press as follows:

1. Read the strings from the JTextField objects and convert them to floating point numbers (hints below).

2. Calculate the result by applying the appropriate operation, and write the output to the JLabel (or an error if the input cannot be converted to a number).

Hints:

1. Make sure all the buttons send events to the JPanel class (you should call addActionListener on each one-see Greeter.java).

2. Convert the strings to floats using the Float.parseFloat( String ) method. This returns a float, but throws an exception if it can't do the conversion. You can use the code below in your solution:

try {
// get the operands
float val1 = Float.parseFloat(input1.getText());
float val2 = Float.parseFloat(input2.getText());

float result = 0;
// calculate result here...
answer.setText("Answer: " + result);
} catch(Exception e) {
answer.setText("invalid input");
}

What this does is try to execute all the code in the try block. If it succeeds, the catch block is ignored. If an exception is thrown by any of the code in the try block, the catch block is executed. The details of the exception can be accessed using the local variable e-in this case we don't query this and just give out a blanket error message. We will cover exceptions in more detail next week.

3. Think carefully about how you use the code in hint 2. Would it be a good idea to cut and paste this four times into the action Performed method, once for each button? Probably not. Much better would be to write a single method which reads the input and performs the calculation. You could define an enumeration for the operations, and then pass that into a calculation method. Something like:

enum Operation {
TIMES, PLUS, MINUS, DIVIDE
}

public void actionPerformed(ActionEvent event) {
if(event.getSource() == buttonTimes)
calculate(Operation.TIMES);
else if(event.getSource() == buttonPlus)
calculate(Operation.PLUS);
else if(event.getSource() == buttonMinus)
calculate(Operation.MINUS);
else if(event.getSource() == buttonDivide)
calculate(Operation.DIVIDE);
}

void calculate(Operation op) {
// ... do stuff. A switch statement may be useful here...
}
Academic Honesty!
It is not our intention to break the school's academic policy. Posted solutions are meant to be used as a reference and should not be submitted as is. We are not held liable for any misuse of the solutions. Please see the frequently asked questions page for further questions and inquiries.
Kindly complete the form. Please provide a valid email address and we will get back to you within 24 hours. Payment is through PayPal, Buy me a Coffee or Cryptocurrency. We are a nonprofit organization however we need funds to keep this organization operating and to be able to complete our research and development projects.