JAVA: write a calculator from scratch

catalogue

Calculator function

Various difficulties

Difficulty 1: graphical interface

Difficulty 2: various calculation formulas

Difficulty 3: continuous operation

Difficulty 4: monitor and accurately respond to user clicks

Source code

Calculator function

A simple calculator should have a graphical interface, various buttons and a result display screen. It supports addition, subtraction, multiplication and division, N-power, N-power root, sin, cos, tan and the corresponding inverse sin, cos, tan and log.

Various difficulties

Difficulty 1: graphical interface

Here I choose Java Swing.

1. First build our window with JPane and JFramel. JPanel is a general lightweight container. First define a JPanel panel, and then use panel = new JPanel in the main method; Create a window. Set the color with setBackground.

JPanel panel;
panel = new JPanel;
panel.setBackground(Color.BLUE);

2. Use JTextField to output calculation results. JTextField is a lightweight component that allows editing single line text.

  • The horizontal alignment of JTextField can be set to left alignment, leading alignment, center alignment, right alignment or tail alignment. Right / trailing alignment is useful if the required size of the field text is less than the size assigned to it. This is determined by the setHorizontalAlignment and getHorizontalAlignment methods. The default is leading alignment.

  • JTextField
    • public JTextField(): construct a new TextField. Create the default model, the initial string is null, and the number of columns is set to 0.
    • public JTextField​(String text): construct a new TextField initialized with the specified text. The default model will be created with 0 columns.
    • public JTextField (int. columns): construct a new empty TextField with a specified number of columns. The default model is created and the initial string is set to null.
    • public JTextField​(String text, int, columns): construct a new TextField initialized with the specified text and columns. Create a default model.
    • public JTextField​(Document doc, String text, int, columns): construct a new JTextField, which uses the given text storage model and the given number of columns. This is the constructor provided by other constructors. If the document is null, a default model is created.
  • setHorizontalAlignment
    • Sets the horizontal alignment of the text. Valid keys are:
      
      • JTextField.LEFT
      • JTextField.CENTER
      • JTextField.RIGHT
      • JTextField.LEADING
      • JTextField.TRAILING
      When setting the alignment, invalidate and repeat are called and the PropertyChange event ("horizontalAlignment") is.
  • setFont
    • public void setFont​(Font f): set the current font. This will delete the cached row height and column width to reflect the new font. After base note, call revalidate.
JTextField display;
display = new JTextField(20);
display.setEditable(false);
display.setText(displayText);

3. Create various keys of calculator with JButton

Then add event listeners so that users can give us a value to judge by pressing the key. Use panel add(JButton); Add button to container.

Difficulty 2: various calculation formulas

result = Math.pow(operand2, 2);
result = Math.pow(operand2, 3);
result = Math.sqrt(operand2);
result = Math.sin(operand2*Math.PI/180);
result = Math.cos(operand2*Math.PI/180);
result = Math.tan(operand2*Math.PI/180);
result = Math.log10(operand2);
result = Math.log(operand2);
result = Math.asin(operand2);
result = Math.acos(operand2);
result = Math.atan(operand2);
result = operand2-2*operand2;
result = Math.cbrt(operand2);

sin, cos, tan not only use Math formula here, but also convert the input value from radian system to angle system, and then bring it into calculation.

Difficulty 3: continuous operation

To realize continuous operation, you need to record the results of the first two operations, and then operate in turn. Each operation retains the operation results for the next operation. First define two variables operand1, operand2 to save the value entered by the user, and then define an operator to save the operator entered by the user. Then add the judgment conditions. If the user presses the number, the number will be displayed on the screen. If the user presses the operator + - * /, the existing number on the screen will be recorded as operand1, and then the next number operand2 will be recorded, so the screen should be cleared. The user inputs the second number, presses =, records the number on the screen as operand2, and then calculates and outputs the result. After the operator is defined at the beginning, it is null. It will change only after the user presses the operator, so you can judge whether it is a continuous operation by judging whether the operator is null or not.

//        Judge whether continuous operation
        else if (operator != null){
            displayText = Double.toString(computeResult());
            display.setText(displayText);
            operand1 = Double.parseDouble(displayText);
            shouldAppendDigitToNumber = false;
            operator=String.valueOf(c);
            return;

In fact, I also added a judgment shouldappenddigitttonumber here. If it is true, the next input number will be directly + to the screen (string). If it is false, clear the screen first and then add the number.

    // Used to indicate whether you should re-enter a number or add a number to the back of the screen
    boolean shouldAppendDigitToNumber;

Difficulty 4: monitor and accurately respond to user clicks

The awt package is used here. addActionListener is used to judge the first letter of the key pressed by the user, and if, else, if and else are used to respond to different keys of the user. charAt is Java The contents of the String class of the Lang package. command.charAt(0) returns the first char character of the String of the key pressed by the user, and the result is saved in c. by judging c = = "?" You can determine which button the user pressed.

String (Java 2 Platform SE 5.0) (cuit.edu.cn)

Introduction to JAVA lang package - new era migrant workers 01 - blog Park (cnblogs.com)

  btnEqual.addActionListener(this);

  public void actionPerformed(ActionEvent e) {
        var command = e.getActionCommand();
        char c = command.charAt(0);
        if (isOperand(c)) {
        ...
                          }

(1 message) learn Java awt_ A poetic drunk blog - CSDN blog_ awt

(1 message) Java AWT package_ java. Introduction to AWT package_ Face is a blog for dogs - CSDN blog

Source code

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

class Calculator implements ActionListener {
    // Entire panel
    JPanel panel;
    // Display screen of calculator
    JTextField display;
    // Content in the display
    String displayText;
    // Save the first number entered by the user
    Double operand1;
    // Save the operation symbols entered by the user:+- × ÷
    String operator;
    // Used to indicate whether you should re-enter a number or add a number to the back of the screen
    boolean shouldAppendDigitToNumber;
    // Keys on the calculator
    JButton btnFushu,btnDian,btnLog,btnLn,btnAdd,btnSubtract,btnChen,btnChu,btnAc,btnEqual;
    JButton btnSin,btnAsin,btnAcos,btnAtan,btnCos,btnTan;
    JButton b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b00;
    JButton btnPingFan3,btnPingFan2,btnPingFanGen,btnPingFanGen3;
        // Generate entire calculator template
    Calculator(){
        panel = new JPanel();
    //  Set background color
        panel.setBackground(Color.BLUE);

    //  Initialize the operator to provide conditions for subsequent judgment of continuous operation
        operator = null;
        displayText = "0";
        display = new JTextField(20);
        display.setEditable(false);
        display.setText(displayText);
        shouldAppendDigitToNumber = false;
        createButtons();
        attachListeners();
        addComponentsToPanel();
                }
    /**
     * Add the screen and keys to the calculator in turn
     */
    void addComponentsToPanel() {
        panel.add(btnEqual);
        panel.add(display);
        panel.add(btnAc);
        panel.add(b0);
        panel.add(b1);
        panel.add(b2);
        panel.add(b3);
        panel.add(b4);
        panel.add(b5);
        panel.add(b6);
        panel.add(b7);
        panel.add(b8);
        panel.add(b9);
        panel.add(btnDian);
        panel.add(b00);
        panel.add(btnFushu);
        panel.add(btnAdd);
        panel.add(btnSubtract);
        panel.add(btnChen);
        panel.add(btnChu);
        panel.add(btnPingFan2);
        panel.add(btnPingFan3);
        panel.add(btnPingFanGen);
        panel.add(btnPingFanGen3);
        panel.add(btnSin);
        panel.add(btnCos);
        panel.add(btnTan);
        panel.add(btnAsin);
        panel.add(btnAcos);
        panel.add(btnAtan);
        panel.add(btnLog);
        panel.add(btnLn);
                                }
    /**
     * Set the reaction of the calculator when the user clicks the key
     */
    void attachListeners() {
        btnAdd.addActionListener(this);
        b1.addActionListener(this);
        b0.addActionListener(this);
        b00.addActionListener(this);
        b2.addActionListener(this);
        b3.addActionListener(this);
        b4.addActionListener(this);
        b5.addActionListener(this);
        b6.addActionListener(this);
        b7.addActionListener(this);
        b8.addActionListener(this);
        b9.addActionListener(this);
        btnEqual.addActionListener(this);
        btnSubtract.addActionListener(this);
        btnChen.addActionListener(this);
        btnChu.addActionListener(this);
        btnAc.addActionListener(this);
        btnPingFan2.addActionListener(this);
        btnPingFan3.addActionListener(this);
        btnPingFanGen.addActionListener(this);
        btnPingFanGen3.addActionListener(this);
        btnSin.addActionListener(this);
        btnCos.addActionListener(this);
        btnTan.addActionListener(this);
        btnLog.addActionListener(this);
        btnLn.addActionListener(this);
        btnDian.addActionListener(this);
        btnAsin.addActionListener(this);
        btnAcos.addActionListener(this);
        btnAtan.addActionListener(this);
        btnFushu.addActionListener(this);
                            }
    /**
     * Create keys (but not "pasted" to the screen)
     */
    void createButtons() {
        b0 = new JButton("0");
        b00 = new JButton("00");
        b1 = new JButton("1");
        b2 = new JButton("2");
        b3 = new JButton("3");
        b4 = new JButton("4");
        b5 = new JButton("5");
        b6 = new JButton("6");
        b7 = new JButton("7");
        b8 = new JButton("8");
        b9 = new JButton("9");
        btnDian = new JButton(".");
        btnAdd = new JButton("+");
        btnEqual = new JButton("=");
        btnSubtract = new JButton("-");
        btnChen = new JButton("×");
        btnChu = new JButton("÷");
        btnAc = new JButton("AC");
        btnPingFan2 = new JButton("Quadratic");
        btnPingFan3 = new JButton("Cubic");
        btnPingFanGen = new JButton("square root");
        btnPingFanGen3 = new JButton("Cube root");
        btnSin = new JButton("Sin");
        btnAsin = new JButton("count ASin");
        btnAcos= new JButton("seek Acos");
        btnAtan = new JButton("have to Atan");
        btnCos = new JButton("Cos");
        btnTan = new JButton("Tan");
        btnLog = new JButton("Commonly used log");
        btnLn = new JButton("Ln");
        btnFushu = new JButton("negative");
        Font f = new Font("Imitation Song Dynasty", Font.BOLD, 20);// Creates a new Font based on the specified Font name, style, and point size
        b0.setFont(f);
        b00.setFont(f);
        b1.setFont(f);
        b2.setFont(f);
        b3.setFont(f);
        b4.setFont(f);
        b5.setFont(f);
        b6.setFont(f);
        b7.setFont(f);
        b8.setFont(f);
        b9.setFont(f);
        btnDian.setFont(f);
        btnAdd.setFont(f);
        btnEqual.setFont(f);
        btnSubtract.setFont(f);
        btnChen.setFont(f);
        btnChu.setFont(f);
        btnAc.setFont(f);
        btnPingFanGen.setFont(f);
        btnPingFan2.setFont(f);
        btnPingFan3.setFont(f);
        btnPingFanGen3.setFont(f);
        btnSin.setFont(f);
        btnAsin.setFont(f);
        btnAcos.setFont(f);
        btnAtan.setFont(f);
        btnCos.setFont(f);
        btnTan.setFont(f);
        btnLog.setFont(f);
        btnLn.setFont(f);
        btnFushu.setFont(f);
                        }
    // main function
    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        JFrame frame = new JFrame("Caculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(calculator.panel);
        frame.setSize(330, 600);
        frame.setLocation(700,300);
        frame.setVisible(true);
                                            }
//    Main judgment methods
    public void actionPerformed(ActionEvent e) {
        var command = e.getActionCommand();
        char c = command.charAt(0);
        if (isOperand(c)) {
            if (shouldAppendDigitToNumber) {
                displayText += command;
            } else {
                displayText = command;
                shouldAppendDigitToNumber = true;
            }
        } else if (c == '=') {
            Double result = computeResult();
            displayText = Double.toString(result);
            operator = null;
            operand1 = null;
            shouldAppendDigitToNumber = false;
        } else if (c == 'A'){
            displayText = "0";
            operator=null;
            operand1 = null;
            shouldAppendDigitToNumber = false;
        }
        else if (c == '.'){
            displayText += command;
            shouldAppendDigitToNumber = true;
        }
        else if (c == 'negative'){
            Double result = computeResult12();
            displayText = Double.toString(result);
            operator = null;
            operand1 = null;
            shouldAppendDigitToNumber = false;
        }
        else if (c == 'two'){
            Double result = computeResult1();
            displayText = Double.toString(result);
            operator = null;
            operand1 = null;
            shouldAppendDigitToNumber = false;
        }
        else if (c == 'three'){
            Double result = computeResult8();
            displayText = Double.toString(result);
            operator = null;
            operand1 = null;
            shouldAppendDigitToNumber = false;
        }
        else if (c == 'S'){
            Double result = computeResult3();
            displayText = Double.toString(result);
            operator = null;
            operand1 = null;
            shouldAppendDigitToNumber = false;
        }
        else if (c == 'count'){
            Double result = computeResult9();
            displayText = Double.toString(result);
            operator = null;
            operand1 = null;
            shouldAppendDigitToNumber = false;
        }
        else if (c == 'seek'){
            Double result = computeResult10();
            displayText = Double.toString(result);
            operator = null;
            operand1 = null;
            shouldAppendDigitToNumber = false;
        }
        else if (c == 'have to'){
            Double result = computeResult11();
            displayText = Double.toString(result);
            operator = null;
            operand1 = null;
            shouldAppendDigitToNumber = false;
        }
        else if (c == 'C'){
            Double result = computeResult4();
            displayText = Double.toString(result);
            operator = null;
            operand1 = null;
            shouldAppendDigitToNumber = false;
        }
        else if (c == 'T'){
            Double result = computeResult5();
            displayText = Double.toString(result);
            operator = null;
            operand1 = null;
            shouldAppendDigitToNumber = false;
        }
        else if (c == 'often'){
            Double result = computeResult6();
            displayText = Double.toString(result);
            operator = null;
            operand1 = null;
            shouldAppendDigitToNumber = false;
        }
        else if (c == 'L'){
            Double result = computeResult7();
            displayText = Double.toString(result);
            operator = null;
            operand1 = null;
            shouldAppendDigitToNumber = false;
        }
        else if (c == 'flat'){
            Double result = computeResult2();
            displayText = Double.toString(result);
            operator = null;
            operand1 = null;
            shouldAppendDigitToNumber = false;
        }
        else if (c == 'stand'){
            Double result = computeResult13();
            displayText = Double.toString(result);
            operator = null;
            operand1 = null;
            shouldAppendDigitToNumber = false;
        }
//        Judge whether continuous operation
        else if (operator != null){
            displayText = Double.toString(computeResult());
            display.setText(displayText);
            operand1 = Double.parseDouble(displayText);
            shouldAppendDigitToNumber = false;
            operator=String.valueOf(c);
            return;
        }
        else {
            operand1 = Double.parseDouble(displayText);
            shouldAppendDigitToNumber = false;
            operator = command;
        }
        display.setText(displayText);
    }
    /**
     * Calculation results
     */
    Double computeResult() {
        Double operand2 = Double.parseDouble(displayText);
        Double result=0.0;
        switch (operator) {
            case "+":
                result = addNumbers(operand1, operand2);
                break;
            case "-":
                result = SubtractNumbers(operand1, operand2);
                break;
            case "×":
                result = chenNumbers(operand1, operand2);
                break;
            case "÷":
                result = chuNumbers(operand1, operand2);
                break;
                            }
        return result;
                            }
    Double computeResult1() {
        double operand2 = Double.parseDouble(displayText);
        double result;
        result = Math.pow(operand2, 2);
        return result;
                            }
    Double computeResult8() {
        double operand2 = Double.parseDouble(displayText);
        double result;
        result = Math.pow(operand2, 3);
        return result;
    }
    Double computeResult2() {
        double operand2 = Double.parseDouble(displayText);
        double result;
        result = Math.sqrt(operand2);
        return result;
                             }
    Double computeResult3() {
        double operand2 = Double.parseDouble(displayText);
        double result;
        result = Math.sin(operand2*Math.PI/180);
        return result;
    }
    Double computeResult4() {
        double operand2 = Double.parseDouble(displayText);
        double result;
        result = Math.cos(operand2*Math.PI/180);
        return result;
    }
    Double computeResult5() {
        double operand2 = Double.parseDouble(displayText);
        double result;
        result = Math.tan(operand2*Math.PI/180);
        return result;
    }
    Double computeResult6() {
        double operand2 = Double.parseDouble(displayText);
        double result;
        result = Math.log10(operand2);
        return result;
    }
    Double computeResult7() {
        double operand2 = Double.parseDouble(displayText);
        double result;
        result = Math.log(operand2);
        return result;
    }
    Double computeResult9() {
        double operand2 = Double.parseDouble(displayText);
        double result;
        result = Math.asin(operand2);
        return result;
    }
    Double computeResult10() {
        double operand2 = Double.parseDouble(displayText);
        double result;
        result = Math.acos(operand2);
        return result;
    }
    Double computeResult11() {
        double operand2 = Double.parseDouble(displayText);
        double result;
        result = Math.atan(operand2);
        return result;
    }
    Double computeResult12() {
        double operand2 = Double.parseDouble(displayText);
        double result;
        result = operand2-2*operand2;
        return result;
    }
    Double computeResult13() {
        double operand2 = Double.parseDouble(displayText);
        double result;
        result = Math.cbrt(operand2);
        return result;
    }
    Double addNumbers(Double a, Double b) {
        return a + b;
                                          }
    Double SubtractNumbers(Double a, Double b) {
        return a - b;
                                                 }
    Double chenNumbers(Double a, Double b) {
        return a * b;
                                             }
    Double chuNumbers(Double a, Double b) {
        return a / b;
                                           }
    /**
     * Judge whether it is a number (like 0123) or an operator (+ - = or the like)
     */
    boolean isOperand(char c) {
        return Character.isDigit(c);
                                }
}

Tags: Java

Posted by spawnark on Fri, 15 Apr 2022 06:30:52 +0930