Calculatorusingjava

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

import javax.swing.

*;

import java.awt.*;

import java.awt.event.*;

public class CalculatorApplet extends JFrame implements ActionListener {

private JTextField displayField;

private JButton[] buttons;

private String[] buttonLabels = {

"7", "8", "9", "/",

"4", "5", "6", "*",

"1", "2", "3", "-",

"C", "0", "=", "+"

};

public CalculatorApplet() {

setTitle("Calculator");

setSize(300, 400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new BorderLayout());

displayField = new JTextField();

displayField.setEditable(false);
add(displayField, BorderLayout.NORTH);

JPanel buttonPanel = new JPanel(new GridLayout(4, 4));

buttons = new JButton[buttonLabels.length];

for (int i = 0; i < buttonLabels.length; i++) {

buttons[i] = new JButton(buttonLabels[i]);

buttons[i].addActionListener(this);

buttonPanel.add(buttons[i]);

add(buttonPanel, BorderLayout.CENTER);

public void actionPerformed(ActionEvent ae) {

String command = ae.getActionCommand();

if ("0123456789".contains(command)) {

displayField.setText(displayField.getText() + command);

} else if (command.equals("C")) {

displayField.setText("");

} else if (command.equals("=")) {

try {

String result = evaluateExpression(displayField.getText());

displayField.setText(result);

} catch (IllegalArgumentException ex) {


displayField.setText("Invalid expression");

} catch (ArithmeticException ex) {

displayField.setText("Division by zero");

} else {

displayField.setText(displayField.getText() + " " + command + " ");

private String evaluateExpression(String expression) {

String[] tokens = expression.split(" ");

if (tokens.length % 2 == 0) {

throw new IllegalArgumentException("Invalid expression");

double result = Double.parseDouble(tokens[0]);

for (int i = 1; i < tokens.length - 1; i += 2) {

String operator = tokens[i];

double operand = Double.parseDouble(tokens[i + 1]);

switch (operator) {

case "+":

result += operand;

break;

case "-":

result -= operand;
break;

case "*":

result *= operand;

break;

case "/":

if (operand == 0) {

throw new ArithmeticException("Division by zero");

result /= operand;

break;

default:

throw new IllegalArgumentException("Invalid operator: " +


operator);

return Double.toString(result);

public static void main(String[] args) {

SwingUtilities.invokeLater(() -> {

CalculatorApplet calculator = new CalculatorApplet();

calculator.setVisible(true);

});

You might also like