Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Department of Software Engineering.

Government College University, Faisalabad.

Assignment 2, May 2024.

Class: BS(SE).

Semester: 2nd Morning.

Course Title: Object Oriented Programming

Roll no: 232680

Instructor: Dr.M.Awais.

Name: Muhammad Saeed Khan

Father Name: Saif Ullah


Code For Calculator Using Java.

Import javax.swing.*;
Import java.awt.*;
Import java.awt.event.ActionEvent;
Import java.awt.event.ActionListener;

Public class ScientificCalculator extends JFrame implements


ActionListener {
// Declare components
JTextField display;
JButton[] buttons;

// Constructor
Public ScientificCalculator() {
// Set up the frame
setTitle(“Scientific Calculator”);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLayout(new BorderLayout());
// Initialize components
Display = new JTextField();
Buttons = new JButton[20];

// Set layout for display


Display.setPreferredSize(new Dimension(400, 50));
Add(display, BorderLayout.NORTH);

// Create buttons
String[] buttonLabels = {“7”, “8”, “9”, “/”, “4”, “5”, “6”,
“*”, “1”, “2”, “3”, “-“, “0”, “.”, “=”, “+”};
JPanel buttonPanel = new JPanel(new GridLayout(4, 4));

For (int I = 0; I < 16; i++) {


Buttons[i] = new JButton(buttonLabels[i]);
Buttons[i].addActionListener(this);
buttonPanel.add(buttons[i]);
}

Add(buttonPanel, BorderLayout.CENTER);

setVisible(true);
}

// Action performed method


Public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
If (command.charAt(0) >= ‘0’ && command.charAt(0) <=
‘9’ || command.equals(“.”)) {
Display.setText(display.getText() + command);
} else if (command.charAt(0) == ‘C’) {
Display.setText(“”);
} else if (command.charAt(0) == ‘=’) {
// Calculate result
String result = evaluateExpression(display.getText());
Display.setText(result);
} else {
Display.setText(display.getText() + command);
}
}

// Evaluate expression method


Public String evaluateExpression(String expression) {
// Implement your expression evaluation logic here
Return expression;
}

// Main method
Public static void main(String[] args) {
New ScientificCalculator();
}
}

You might also like