Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
13 kB
1
Indexable
Never
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

/*
 * Fix:
 */

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.BLUE);
        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() >= 2)
                {
                    if(screen.getText().substring(screen.getText().length() - 2).equals("--"))
                    {
                        screen.setText(screen.getText());
                        return;
                    }
                }
                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 = eval(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 eval(final String str) {
        return new Object() {
            int pos = -1, ch;
            
            void nextChar() {
                ch = (++pos < str.length()) ? str.charAt(pos) : -1;
            }
            
            boolean eat(int charToEat) {
                while (ch == ' ') nextChar();
                if (ch == charToEat) {
                    nextChar();
                    return true;
                }
                return false;
            }
            
            double parse() {
                nextChar();
                double x = parseExpression();
                if (pos < str.length()) throw new RuntimeException("Unexpected: " + (char)ch);
                return x;
            }
            
            // Grammar:
            // expression = term | expression `+` term | expression `-` term
            // term = factor | term `*` factor | term `/` factor
            // factor = `+` factor | `-` factor | `(` expression `)` | number
            //        | functionName `(` expression `)` | functionName factor
            //        | factor `^` factor
            
            double parseExpression() {
                double x = parseTerm();
                for (;;) {
                    if      (eat('+')) x += parseTerm(); // addition
                    else if (eat('-')) x -= parseTerm(); // subtraction
                    else return x;
                }
            }
            
            double parseTerm() {
                double x = parseFactor();
                for (;;) {
                    if      (eat('*')) x *= parseFactor(); // multiplication
                    else if (eat('/')) x /= parseFactor(); // division
                    else return x;
                }
            }
            
            double parseFactor() {
                if (eat('+')) return +parseFactor(); // unary plus
                if (eat('-')) return -parseFactor(); // unary minus
                
                double x;
                int startPos = this.pos;
                if (eat('(')) { // parentheses
                    x = parseExpression();
                    if (!eat(')')) throw new RuntimeException("Missing ')'");
                } else if ((ch >= '0' && ch <= '9') || ch == '.') { // numbers
                    while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
                    x = Double.parseDouble(str.substring(startPos, this.pos));
                } else if (ch >= 'a' && ch <= 'z') { // functions
                    while (ch >= 'a' && ch <= 'z') nextChar();
                    String func = str.substring(startPos, this.pos);
                    if (eat('(')) {
                        x = parseExpression();
                        if (!eat(')')) throw new RuntimeException("Missing ')' after argument to " + func);
                    } else {
                        x = parseFactor();
                    }
                    if (func.equals("sqrt")) x = Math.sqrt(x);
                    else if (func.equals("sin")) x = Math.sin(Math.toRadians(x));
                    else if (func.equals("cos")) x = Math.cos(Math.toRadians(x));
                    else if (func.equals("tan")) x = Math.tan(Math.toRadians(x));
                    else throw new RuntimeException("Unknown function: " + func);
                } else {
                    throw new RuntimeException("Unexpected: " + (char)ch);
                }
                
                if (eat('^')) x = Math.pow(x, parseFactor()); // exponentiation
                
                return x;
            }
        }.parse();
    }

}