Objective: Design a calculator using event-driven programming paradigm of Java with the following options.
a) Decimal manipulations
b) Scientific manipulations
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField display;
private String currentInput = "";
private double result = 0;
private String operator = "";
private boolean isScientific = false;
public Calculator() {
setTitle("Calculator");
setSize(400, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
display = new JTextField();
display.setFont(new Font("Arial", Font.BOLD, 20));
display.setHorizontalAlignment(JTextField.RIGHT);
display.setEditable(false);
add(display, BorderLayout.NORTH);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5, 4, 5, 5));
String[] buttons = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+", "C", "sin", "cos", "sqrt"};
for (String text : buttons) {
JButton button = new JButton(text);
button.setFont(new Font("Arial", Font.BOLD, 18));
button.addActionListener(this);
panel.add(button);
}
add(panel, BorderLayout.CENTER);
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.matches("[0-9.]")) {
currentInput += command;
display.setText(currentInput);
} else if (command.matches("[+\\-*/]") || command.equals("sqrt")) {
operator = command;
result = Double.parseDouble(currentInput);
currentInput = "";
} else if (command.equals("=")) {
double num = Double.parseDouble(currentInput);
switch (operator) {
case "+": result += num; break;
case "-": result -= num; break;
case "*": result *= num; break;
case "/": result /= num; break;
case "sqrt": result = Math.sqrt(result); break;
}
display.setText(String.valueOf(result));
currentInput = "";
} else if (command.equals("C")) {
currentInput = "";
result = 0;
operator = "";
display.setText("");
} else if (command.equals("sin")) {
result = Math.sin(Math.toRadians(Double.parseDouble(currentInput)));
display.setText(String.valueOf(result));
} else if (command.equals("cos")) {
result = Math.cos(Math.toRadians(Double.parseDouble(currentInput)));
display.setText(String.valueOf(result));
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new Calculator().setVisible(true);
});
}
}
Output:
No comments:
Post a Comment