Untitled

mail@pastecode.io avatar
unknown
java
a year ago
13 kB
2
Indexable
Never
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayDeque;
import java.util.Deque;

import javax.swing.*;

public class Calculator {
    public static void main(String[] args) {
        JFrame cw = new JFrame();
        cw.setTitle("Calculator");
        cw.setPreferredSize(new Dimension(455, 638));
        cw.setVisible(true);
        cw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        cw.getContentPane().setBackground(Color.WHITE);
        cw.setResizable(false);
        Container C = cw.getContentPane();
        C.setLayout(null);
        int counter = 1;

        JPanel backgroundJPanel = new JPanel();
        backgroundJPanel.setBackground(Color.BLUE);
        backgroundJPanel.setBounds(0, 0, 440, 600);



        JTextArea screen = new JTextArea("0");
        screen.setBounds(20, 420 - 210 - 190, 400, 160);
        screen.setBackground(Color.YELLOW);
        screen.setFont(new Font("Arial", Font.BOLD, 22));
        screen.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        screen.setLineWrap(true);
        screen.setWrapStyleWord(false);
        screen.setOpaque(true);
        screen.setEditable(false);
        screen.setHighlighter(null);
        screen.setAlignmentX(JTextArea.LEFT_ALIGNMENT);
        screen.setAlignmentY(JTextArea.BOTTOM_ALIGNMENT);
        cw.add(screen);

        CalculatorButton zeroButton = new CalculatorButton(20, 700 - 190, 100, 70, "0", Color.YELLOW);
        cw.add(zeroButton.myButton);
        CalculatorButton periodButton = new CalculatorButton(120, 700 - 190, 100, 70, ".", Color.YELLOW);
        cw.add(periodButton.myButton);
        CalculatorButton equalsButton = new CalculatorButton(220, 700 - 190, 100, 70, "=", Color.YELLOW);
        cw.add(equalsButton.myButton);
        CalculatorButton plusButton = new CalculatorButton(320, 700 - 190, 100, 70, "+", Color.YELLOW);
        cw.add(plusButton.myButton);
        CalculatorButton minusButton = new CalculatorButton(320, 630 - 190, 100, 70, "-", Color.YELLOW);
        cw.add(minusButton.myButton);
        CalculatorButton multiplyButton = new CalculatorButton(320, 560 - 190, 100, 70, "*", Color.YELLOW);
        cw.add(multiplyButton.myButton);
        CalculatorButton divideButton = new CalculatorButton(320, 490 - 190, 100, 70, "/", Color.YELLOW);
        cw.add(divideButton.myButton);
        CalculatorButton clearButton = new CalculatorButton(320, 420 - 190, 100, 70, "CE", Color.YELLOW);
        cw.add(clearButton.myButton);
        CalculatorButton powerButton = new CalculatorButton(220, 420 - 190, 100, 70, "x^y", Color.YELLOW);
        cw.add(powerButton.myButton);
        CalculatorButton RparenthesisButton = new CalculatorButton(120, 420 - 190, 100, 70, ")", Color.YELLOW);
        cw.add(RparenthesisButton.myButton);
        CalculatorButton LparenthesisButton = new CalculatorButton(20, 420 - 190, 100, 70, "(", Color.YELLOW);
        cw.add(LparenthesisButton.myButton);
        for (int row = 1; row <= 3; row++) {
            for (int column = 0; column < 3; column++) {
                CalculatorButton numberButton = new CalculatorButton(20 + (100 * column), 700 - (70 * row) - 190, 100, 70,
                        counter + "", Color.YELLOW);
                cw.add(numberButton.myButton);
                final Integer innercounter = new Integer(counter);
                numberButton.myButton.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if ((screen.getText().substring(screen.getText().length() - 1).equals("0"))
                                && screen.getText().length() == 1)
                            screen.setText("");
                        screen.setText(screen.getText() + innercounter);
                    }

                });
                counter++;
            }
        }

        LparenthesisButton.myButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if ((screen.getText().substring(screen.getText().length() - 1).equals("0"))
                        && screen.getText().length() == 1)
                    screen.setText("");
                screen.setText(screen.getText() + "(");
            }

        });
        RparenthesisButton.myButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if ((screen.getText().substring(screen.getText().length() - 1).equals("0"))
                        && screen.getText().length() == 1)
                    screen.setText("");
                screen.setText(screen.getText() + ")");
            }

        });
        powerButton.myButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (isNumber(screen.getText().substring(screen.getText().length() - 1)) ||
                        screen.getText().substring(screen.getText().length() - 1).equals(")"))
                    screen.setText(screen.getText() + "^");
            }

        });
        periodButton.myButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (isNumber(screen.getText().substring(screen.getText().length() - 1)))
                    screen.setText(screen.getText() + ".");
            }

        });
        zeroButton.myButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if ((screen.getText().substring(screen.getText().length() - 1).equals("0"))
                        && screen.getText().length() == 1)
                    return;
                screen.setText(screen.getText() + "0");
            }

        });
        plusButton.myButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (isNumber(screen.getText().substring(screen.getText().length() - 1)) ||
                        screen.getText().substring(screen.getText().length() - 1).equals(")"))
                    screen.setText(screen.getText() + "+");
            }

        });
        minusButton.myButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if ((screen.getText().substring(screen.getText().length() - 1).equals("0"))
                        && screen.getText().length() == 1)
                    screen.setText("");

                if(screen.getText().length() == 0)
                    screen.setText(screen.getText() + "-");
                else
                {
                    if (!screen.getText().substring(screen.getText().length() - 1).equals("."))
                        screen.setText(screen.getText() + "-");
                }
            }

        });
        multiplyButton.myButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (isNumber(screen.getText().substring(screen.getText().length() - 1)) ||
                        screen.getText().substring(screen.getText().length() - 1).equals(")"))
                    screen.setText(screen.getText() + "*");
            }

        });
        divideButton.myButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (isNumber(screen.getText().substring(screen.getText().length() - 1)) ||
                        screen.getText().substring(screen.getText().length() - 1).equals(")"))
                    screen.setText(screen.getText() + "/");
            }

        });
        clearButton.myButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                screen.setText("0");
            }

        });
        equalsButton.myButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                double ans = evaluate(screen.getText());
                if((ans+"").equals("0.0"))
                {
                    screen.setText("0");
                } else
                {
                    screen.setText("" + ans);
                }
            }

        });
        
        cw.add(backgroundJPanel);
        cw.pack();
        cw.setVisible(true);
        cw.validate();
    }

    public static boolean isNumber(String str) {
        try {
            Double.parseDouble(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public static double evaluate(String expression) {
        Deque<Double> operands = new ArrayDeque<>();
        Deque<Character> operators = new ArrayDeque<>();
        Deque<Character> precOperators = new ArrayDeque<>();
        precOperators.push('('); // Push an opening parenthesis to ensure all operators are popped
    
        for (int i = 0; i < expression.length(); i++) {
            char c = expression.charAt(i);
            if (Character.isDigit(c) || c == '.') {
                // Parse the number and push it to the operand stack
                int j = i;
                while (j < expression.length() && (Character.isDigit(expression.charAt(j)) || expression.charAt(j) == '.')) {
                    j++;
                }
                double num = Double.parseDouble(expression.substring(i, j));
                operands.push(num);
                i = j - 1;
            } else if (c == '+' || c == '-' || c == '*' || c == '/' || c == '^' || c == '(') {
                // Check if the '-' operator denotes a negative number or a subtraction
                // operation
                if (c == '-' && (i == 0 || (!Character.isDigit(expression.charAt(i - 1)) && expression.charAt(i - 1) != ')'))) {
                    // The '-' operator denotes a negative number, so parse the number and push it
                    // to the operand stack
                    int j = i + 1;
                    while (j < expression.length() && (Character.isDigit(expression.charAt(j)) || expression.charAt(j) == '.')) {
                        j++;
                    }
                    double num = Double.parseDouble(expression.substring(i, j));
                    operands.push(num);
                    i = j - 1;
                } else {
                    // Push the operator to the operator stack in order of precedence
                    while (hasPrecedence(c, precOperators.peek())) {
                        char op = precOperators.pop();
                        double b = operands.pop();
                        double a = operands.pop();
                        double result = applyOp(op, a, b);
                        operands.push(result);
                    }
                    precOperators.push(c);
                }
            } else if (c == ')') {
                // Pop operators and operands until we reach the matching '('
                while (precOperators.peek() != '(') {
                    char op = precOperators.pop();
                    double b = operands.pop();
                    double a = operands.pop();
                    double result = applyOp(op, a, b);
                    operands.push(result);
                }
                precOperators.pop(); // Discard the '('
            } else if (c == ' ') {
                // Ignore whitespace
            } else {
                throw new IllegalArgumentException("Invalid operator: " + c);
            }
        }
    
        // Perform any remaining operations
        while (precOperators.size() > 1) {
            char op = precOperators.pop();
            double b = operands.pop();
            double a = operands.pop();
            double result = applyOp(op, a, b);
            operands.push(result);
        }
    
        return operands.pop();
    }

    public static boolean hasPrecedence(char op1, char op2) {
        if (op2 == '(' || op2 == ')') {
            return false;
        }
        if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) {
            return false;
        }
        if (op1 == '^' && (op2 == '*' || op2 == '/' || op2 == '+' || op2 == '-')) {
            return false;
        }
        return true;
    }

    public static double applyOp(char op, double a, double b) {
        switch (op) {
            case '+':
                return a + b;
            case '-':
                return a - b;
            case '*':
                return a * b;
            case '/':
                if (b == 0) {
                    throw new ArithmeticException("Division by zero");
                }
                return a / b;
            case '^':
                return Math.pow(a, b);
        }
        return 0;
    }
}