Calculator

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

* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.

txt to change this


license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this
template
*/
package scientificcal;

/**
*
* @author ACER
*/

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

public class ScientificCalculator extends JFrame implements ActionListener {


private JTextField displayField;

public ScientificCalculator() {
setTitle("Scientific Calculator");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

displayField = new JTextField();


displayField.setPreferredSize(new Dimension(370, 50));
displayField.setFont(new Font("Arial", Font.PLAIN, 20));
displayField.setHorizontalAlignment(JTextField.RIGHT);
displayField.setEditable(false);

JPanel buttonPanel = new JPanel();


buttonPanel.setLayout(new GridLayout(6, 3, 5, 5));

String[] buttonLabels = {
"sin", "cos", "x^2",
"7", "8", "9",
"4", "5", "6",
"1", "2", "3",
"0", "+", "-",
"*", "/", "="
};

JButton[] 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]);
}

setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));


add(displayField);
add(buttonPanel);
}

public void actionPerformed(ActionEvent e) {


String command = e.getActionCommand();
if (command.equals("=")) {
String expression = displayField.getText();
try {
double result = evaluateExpression(expression);
displayField.setText(Double.toString(result));
} catch (ArithmeticException ex) {
JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
} else if (command.equals("C")) {
displayField.setText("");
} else {
displayField.setText(displayField.getText() + command);
}
}

private double evaluateExpression(String expression) throws ArithmeticException {


expression = expression.replace(" ", ""); // Remove any spaces from the expression

if (expression.isEmpty()) {
throw new ArithmeticException("Empty expression");
}

// Evaluate trigonometric functions (sin, cos)


expression = expression.replaceAll("sin", "Math.sin");
expression = expression.replaceAll("cos", "Math.cos");

// Evaluate x^2 function


expression = expression.replaceAll("x\\^2", "* *");

String[] tokens = expression.split("(?=[-+*/])|(?<=[-+*/])");


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

for (int i = 1; i < tokens.length; 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;
}
}

return result;
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
ScientificCalculator calculator = new ScientificCalculator();
calculator.setVisible(true);
}
});
}
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());


getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 356, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 367, Short.MAX_VALUE)
);

pack();
}// </editor-fold>

/**
* @param args the command line arguments
*/

// Variables declaration - do not modify


// End of variables declaration
}

You might also like