Windows Calculator (based on java)

Catalogue

Personal imformation

Introduction

1.Personal Software Process (PSP) Form

2. Ideas for solving problems

3. Design and Implementation Process

4.Flow chart

5.Code description

6.Results display

7.Summary

8.Restrictions

9.Future plan and improvement direction


Personal imformation

The Link Your Classhttps://bbs.csdn.net/forums/ssynkqtd-04
The Link of Requirement of This Assignmenthttps://bbs.csdn.net/topics/617332156
The Aim of This AssignmentCreate a calculator with a visual interface.
MU STU ID and FZU STU ID

21126721_832102203

ass/assgn1 at main · 832102203wangyiting/ass (github.com)

Introduction

This program provides a basic graphical calculator that supports some mathematical operations and functions.

1.Personal Software Process (PSP) Form

With the PSP form, I was able to better plan and track the time spent in the project, ensuring that the task went on as planned.

Personal Software Process StagesEstimated Time(minutes)Actual Time(minutes)
Planning2025
- Estimate1015
- Reading and Understanding1010
Development200250
- Analysis2025
- Design Spec2020
- Design Review1015
- Coding Standard1020
- Design4030
- Coding6080
- Code Review2025
- Test2035
Reporting8085
- Test Report2020
- Size Measurement1010
- Postmortem & Process Improvement5055
Total300360

2. Ideas for solving problems

Understanding the problem: In the beginning, I thought about the basic and advanced needs of a calculator. Basic functions include addition, subtraction, multiplication, division, zero clearing, advanced functions include power operations, trigonometric functions, etc. I think about the design and implementation of the user interface and how to modularize these functions.

Finding information: I consulted the documentation to learn how to create a Java graphical user interface. I also read the documentation of the math library in order to understand how to perform exponents and trigonometric functions. 

3. Design and Implementation Process

Design:

Select the Java Swing as the GUI framework.
Division functions: text editing area, menu bar (open, save, etc.), toolbar, etc.
To of the basic process of the editor.During the design phase, I drew a simple UI sketch, taking into account the layout of the buttons and user input. I designed a major application class, a class that deals with UI, and a class that deals with computational logic.

Implementation: 

Create the Swing application skeleton.

Implement basic editing functions, such as inserting and deleting charactersI think about how the code is organized to make it easy to understand and maintain.

I designed the button's event handler to make sure the user input is correct and pass it to the computational logic. I implemented the basic features step by step and then added advanced features. I use Git for version control to ensure that the code is iterative and maintainable.

4.Flow chart

5.Code description

Fore-end:

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

public class CalculatorApp extends JFrame {
    private JTextField textField;

    public CalculatorApp() {
        setTitle("Advanced Calculator");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300, 400);
        setLocationRelativeTo(null);

        textField = new JTextField();
        textField.setEditable(false);
        textField.setHorizontalAlignment(JTextField.RIGHT);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(5, 4, 10, 10));

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

        for (String button : buttons) {
            JButton btn = new JButton(button);
            btn.addActionListener(new ButtonClickListener());
            buttonPanel.add(btn);
        }

        setLayout(new BorderLayout());
        add(textField, BorderLayout.NORTH);
        add(buttonPanel, BorderLayout.CENTER);
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new CalculatorApp().setVisible(true);
        });
    }
}

Analyse:
Swing GUI: The front end creates a GUI window using the Swing library, including a text input box and a button grid. The user can enter a mathematical expression in the text input box and then click a button to operate.
JFrame: The CalculatorApp class inherits JFrame and is the main window for GUI applications. The header, size, and close operation of the window are set in the constructor.
JTextField: textField is a text input box that receives the user input expression and displays the calculation results. It is set to read only (setEditable (false)) and text right aligned (setHorizontalAlignment(JTextField.RIGHT)).
JPanel: buttonPanel is a panel for containing a button grid. It uses the GridLayout to arrange the buttons.
JButton: Create the buttons all around, and each button represents a number, operator, or function, such as +, -, sin, cos, etc. Each button has an event listener that triggers the corresponding action after clicking the button.
Layout Management: Use the BorderLayout layout manager to place the text input box at the top of the window and the button grid in the middle.

Back end part:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class CalculatorBackend {
  
    private static final Pattern pattern = Pattern.compile("([-+]?[0-9]*\\.?[0-9]+|[-+*/^()=]|sin|cos|tan)");

    public static double calculateExpression(String expression) {
     
        expression = expression.replaceAll("sin", "s");
        expression = expression.replaceAll("cos", "c");
        expression = expression.replaceAll("tan", "t");

        Matcher matcher = pattern.matcher(expression);
        while (matcher.find()) {
            String token = matcher.group();

        }

        return 0.0; 
    }
}

Analyse:
ButtonClickListener: This is an internal class that implements the ActionListener interface to handle button click events. In the actionPerformed method, different actions are performed based on the text on the button, such as adding the text to the input box or making a calculation.
calculate() Method: When the user clicks the "=" button, the calculate() method is called. It takes the expression in the text input box, replaces the abbreviated function (e. g., sin, cos, tan) as a single letter (s, c, t), and then calls the eval () method to calculate the expression.
Eval () method: This is a recursive descent parser for calculating mathematical expressions. It supports numbers, four operations (plus, minus, multiply, division), parentheses, and trigonometric functions (sin, cos, tan), and power operations (^). It gradually resolves the expression from left to right, builds the expression tree, and calculates the final result.

 Full code:


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

public class CalculatorApp extends JFrame {
    private JTextField textField;

    public CalculatorApp() {
        setTitle("Advanced Calculator");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300, 400);
        setLocationRelativeTo(null);

        textField = new JTextField();
        textField.setEditable(false);
        textField.setHorizontalAlignment(JTextField.RIGHT);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(5, 4, 10, 10));

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

        for (String button : buttons) {
            JButton btn = new JButton(button);
            btn.addActionListener(new ButtonClickListener());
            buttonPanel.add(btn);
        }

        setLayout(new BorderLayout());
        add(textField, BorderLayout.NORTH);
        add(buttonPanel, BorderLayout.CENTER);
    }

    private class ButtonClickListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            JButton source = (JButton) e.getSource();
            String buttonText = source.getText();

            if (buttonText.equals("=")) {
                calculate();
            } else {
                textField.setText(textField.getText() + buttonText);
            }
        }

        private void calculate() {
            try {
                String expression = textField.getText();
                expression = expression.replaceAll("sin", "s");
                expression = expression.replaceAll("cos", "c");
                expression = expression.replaceAll("tan", "t");
                double result = eval(expression);
                textField.setText(String.valueOf(result));
            } catch (Exception ex) {
                textField.setText("Error");
            }
        }

        private double eval(String expression) {
            return new Object() {
                int pos = -1, ch;

                void nextChar() {
                    ch = (++pos < expression.length()) ? expression.charAt(pos) : -1;
                }

                boolean isDigit() {
                    return Character.isDigit(ch);
                }

                double parse() {
                    nextChar();
                    double x = parseExpression();
                    if (pos < expression.length()) throw new RuntimeException("Unexpected: " + (char) ch);
                    return x;
                }

                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 if (eat('^')) x = Math.pow(x, parseFactor()); // exponentiation
                        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();
                        eat(')');
                    } else if (isDigit() || ch == '.') { // numbers
                        while (isDigit()) nextChar();
                        x = Double.parseDouble(expression.substring(startPos, this.pos));
                    } else if (eat('s')) { // sine function
                        x = Math.sin(parseFactor());
                    } else if (eat('c')) { // cosine function
                        x = Math.cos(parseFactor());
                    } else if (eat('t')) { // tangent function
                        x = Math.tan(parseFactor());
                    } else {
                        throw new RuntimeException("Unexpected: " + (char) ch);
                    }

                    return x;
                }

                boolean eat(int charToEat) {
                    while (Character.isWhitespace(ch)) nextChar();
                    if (ch == charToEat) {
                        nextChar();
                        return true;
                    }
                    return false;
                }
            }.parse();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new CalculatorApp().setVisible(true);
        });
    }
}

User interface:

Create a GUI using Java's Swing library, including a window and a text box for displaying expressions and results, as well as a button panel.
The window is titled "Advanced Calculator" and is 300x400 pixels in size.


Button panel:

Buttons containing numbers, basic operators, and some special functions are laid out using GridLayout.
Special functions include trigonometric functions (sin, cos, tan) and exponential operations (^).


Button click event:

Respond to button clicks by adding a ButtonClickListener event listener for each button.
The button click event mainly updates the contents of the text box, adding numbers and operators to the current expression.


Calculation logic:

The calculate method handles the equals button click event and passes the expression to the eval method for evaluation.
The eval method is a recursive descent parser used to parse and evaluate mathematical expressions, supporting fundamental operations, trigonometric functions, and exponential operations.


Error handling:

Basic Error handling is provided, such as displaying "Error" when an exception occurs during calculation.


Main method:

The main method used SwingUtilities invokeLater ensure on the event dispatching thread to create and display window, in order to avoid multithreading issues.

6.Results display

assigment

8+5=13.0

8-5=3.0

8*5=40.0

8/5=1.6

sin5=-0.95892

cos5=0.28366

tan5=-0.38052

8^5=32768

The result is correct.

7.Summary

In this project, I have successfully created a calculator with a visual interface. I learned how to build a simple GUI application using Java Swing.By meeting the requirements of the project, using Java language,AWT and Swing , realizing basic functions such as addition, subtraction, multiplication and division, and gradually adding advanced functions such as exponential and trigonometry.

I recorded my work process, design ideas, and key code. This project not only helped me improve my coding skills, but also exercised my thinking and organizational skills when designing and implementing the project.By versioning using Git I was able to manage code changes effectively and also learned how to effectively organize the code, process user input and implement mathematical operations. 
 

8.Restrictions

User experience:When users enter complex expressions, they may find that the text box on the UI is not large enough. Consider implementing an automatic extension of the text box or providing a larger text box to accommodate longer expressions.
Error handling:Error handling is relatively simple, just displaying "Error" in a text box. A more detailed error message might be more helpful, such as indicating what the specific error the user entered was.
UI Design:Button layouts and labels may not be intuitive enough. User understanding and usage can be improved with more explicit labeling or layout adjustments.
Scientific notation and large numbers support:Current implementations may not be able to handle very large or very small numbers, nor can they handle scientific notation. When dealing with a larger range of numbers, further improvements to the calculation engine may be required.


9.Future plan and improvement direction

Richer features:Consider adding some advanced math operations, such as logarithms, square roots, etc., to provide more comprehensive functionality.
Variables and storage:Supports the function of variables, and users can define variables and use them in expressions. This can be achieved by introducing a variable resolver and storage.
Improved error handling:Provide more detailed error information to help users understand and correct input errors.
Improved user interface:Consider adding other UI elements, such as menus or toolbars, to provide more options and functionality.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值