Java course design - a hundred lines of code to realize a simple calculator

                                         成绩: __________

Java programming
engineering practice

——Design of a simple calculator

College, Department Computer and Software School Professional Information Security
Name
Instructor

June 11, 2022

Contents:
1. Design introduction 2
1. Design background 2
2. Development tools and environment 2
(1) Development tools and introduction 2
(2) Development environment 2
2. Related work 2 1.
Design basis 2
2. Functional requirements 2
3. System Design 3
3. Design Principle 3
1. Package and Class Description 3
2. Simple Calculator Source Code List 3
4. Implementation Results 6
1. Program Interface 6
2. Test Case 7
3. Running Results 7
5. Design Experience 9

1. Design introduction
1. Design background
With the increasing material living standards and the improvement of basic computing needs in daily life. Nowadays, with the rapid development of the network, the demand for computing power is increasing, and the efficiency and performance of computing are closely related to people's lives. In this regard, a calculator that brings convenience to people's lives is developed by using the Java language, in order to improve the calculation of data. The system realizes the operations of addition, subtraction, multiplication and division of logarithms.
2. Development tools and environment
(1) Development tools and introduction
Visual Studio Code (referred to as "VS Code") is a program running on Mac OS X, Windows and Linux officially announced by Microsoft at the Build developer conference on April 30, 2015. , a cross-platform source code editor for writing modern web and cloud apps,[2] runs on the desktop and is available for Windows, macOS, and Linux. It has built-in support for JavaScript, TypeScript, and Node.js, and has a rich ecosystem of extensions for other languages ​​(such as C++, C#, Java, Python, PHP, Go) and runtimes (such as .NET and Unity).
(2) Development environment: window10 system, Visual Studio Code1.67.2, JDK17.0.2.
2. Related work
1. Design basis
Use Java Swing GUI to design and write a simple calculator, add event listener, and input the values ​​and operators involved in the calculation through the mouse to achieve the purpose of four arithmetic operations.
2. Functional requirements
Graphical user interface, a simple calculator designed, the user enters the values ​​and operators involved in the calculation through the mouse, and performs four arithmetic operations, as follows:
(1) Click the number buttons (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) on the "Calculator" to set the value involved in the operation
(2) Click the "Calculator" The operator button (+, -, *, /) on the "Tool" selects the operator at the same time, saves the previous number, and enters the input field for subsequent input.
(3) Click the "=" button on the "Calculator" with the mouse to output the result of the operation.
(4) Click the "clear" button on the "Calculator" to clear the numbers in the input box.
3. System design
A simple calculator is mainly composed of interface components, component event listeners and processing programs, as shown in Figure 2-1. The realization of its functions can be divided into the following steps:
(1) Create a Java project (this version is JDK 17.0.2)
(2) Create a frame, panel and initialization
(3) Create a UI component and add it to the corresponding panel Medium
(4) Register listener, add event response logic
(5) Computing logic implementation

3. Design principles
1. Description of packages and classes
package start;\package package util that saves the main function implementation code
;\package that saves constants
public class Const\customizes the class that saves constants
public class calculator \customizes the implementation of the calculator main Functional class
2. Source code list of simple calculator
①Import components

package start;
import javax.swing.*;
import util.Const;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

②Create part of the code of the Const class

public class Const {
    public static final int FRAME_W = 300;//得到窗体中心点
    public static final int FRAME_H = 300;
    public static final int SCREEN_W = Toolkit.getDefaultToolkit().getScreenSize().width;
    public static final int SCREEN_H = Toolkit.getDefaultToolkit().getScreenSize().height;

    public static final int Frame_X = (SCREEN_W-FRAME_W)/2;
    public static final int Frame_Y = (SCREEN_H-FRAME_H)/2;

    public static final String TITLE = "计算器";
}
 ③calculator类中的部分代码
public class calculator extends JFrame implements ActionListener{
    /**********************北面的控件***********************/
    private JPanel jp_north = new JPanel();
    private JTextField input_text = new JTextField();
    private JButton c_Btn = new JButton("Clear");
     /**********************中间的控件***********************/
     private JPanel jp_center = new JPanel();
     public calculator() throws HeadlessException{//显示窗体
        this.init();
        this.addNorthComponent();
        this.addCenterButton();
    }
    //初始化的方法
    public void init(){
        this.setTitle(Const.TITLE);
        this.setSize(Const.FRAME_W, Const.FRAME_H);
        this.setLayout(new BorderLayout());
        this.setResizable(false);
        this.setLocation(Const.Frame_X,Const.Frame_Y);//设置框架在屏幕的位置
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭键
    }
    //主方法
    public static void main(String[] args) {
        calculator Calculator = new calculator();
        Calculator.setVisible(true);
    }

}
④添加控件和按钮的代码
    //添加北面的控件
    public void addNorthComponent(){
        this.input_text.setPreferredSize(new Dimension(200,30));//设置文本框大小
        jp_north.add(input_text);//加文本框

        this.c_Btn.setForeground(Color.RED);//设置按钮颜色
        jp_north.add(c_Btn);//加按钮
        c_Btn.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                input_text.setText("");
            }
        });

        this.add(jp_north,BorderLayout.NORTH);//将面板加到框架北侧
    }
    //添加中间按钮
    public void addCenterButton(){
        String btn_text = "123+456-789*0.=/";
        String regex = "[\\+\\-*/.=]";//正则表达式
        this.jp_center.setLayout(new GridLayout(4,4));//4*4的布局
        for(int i=0;i<16;i++){//在面板中加按钮
            String tmp  = btn_text.substring(i,i+1);
            JButton btn = new JButton();
            btn.setText(tmp);//给按钮加文字
            if(tmp.matches(regex)){//如果正则匹配
                    btn.setFont(new Font("粗体",Font.BOLD,20));
                    btn.setForeground(Color.RED);
                }
            btn.addActionListener(this);//添加按钮监听器
            jp_center.add(btn);
        }
        this.add(jp_center,BorderLayout.CENTER);//将面板加载框架布局的中间位置
    }
⑤添加事件监听器和逻辑运算代码
    private String firstInput = null;
    private String operator = null;
    //给按钮添加监听事件
    public void actionPerformed(ActionEvent e){
        String clickStr = e.getActionCommand();
        if(".0123456789".indexOf(clickStr)!=-1){//数字输入
            this.input_text.setText(input_text.getText() + clickStr);
            this.input_text.setHorizontalAlignment(JTextField.RIGHT);
        }
        else if(clickStr.matches("[\\+\\-*/]{1}")){//运算符输入
            operator = clickStr;
            firstInput = this.input_text.getText();
            this.input_text.setText("");
        }
        else if(clickStr.equals("=")){//等号输入
            Double a = Double.valueOf(firstInput);
            Double b = Double.valueOf(this.input_text.getText());
            Double res = null;
            switch (operator){//运算主体
                case "+":
                res = a + b;
                break;
                case "-":
                res = a - b;
                break;
                case "*":
                res = a * b;
                break;
                case "/":
                if(b!=0){
                    res = a/b;
                }
                else{
                    this.input_text.setText("除数不能为0!请清空!");
                }
                break;
            }
            this.input_text.setText(res.toString());
        }
    }

4. Achievement results
1. Program interface
The operation interface of the simple calculator is shown in Figure 3-1.
insert image description here

Figure 3-1 Calculator running interface
2. Test case
(1) Clear the current input value, for example: calculate 7+23, the output result is 30.0.
(2) Clear the currently input value, for example: calculate 7-23, the output result is -16.0.
(3) Clear the currently input value, for example: calculate 7*23, the output result is 161.0.
(4) Clear the currently input value, for example: calculate 7/23, the output result is 0.30434782608695654.
3. Operation result
(1) Input 7 and 23 to perform addition operation, as shown in Figure 3-2, Figure 3-3 and Figure 3-4. Only output the result below.
insert image description here

Figure 3-2 Input 7
insert image description here

Figure 3-3 Input 23
insert image description here

Figure 3-4 The result is displayed as 30.0

(2) Input 7 and 23 to perform subtraction, as shown in Figure 3-5.
insert image description here

Figure 3-5 The result of "7-23" is displayed as -16.0

(3) Input 7 and 23 to perform multiplication, as shown in Figure 3-6
insert image description here

Figure 3-6 The result of "7*3" is displayed as 161.9

(4) Input 7 and 23 to perform division operation, as shown in Figure 3-7.
insert image description here

Figure 3-7 "7/23" shows 0.30434782608695654
V. Design Experience
From my point of view, the purpose of the course design is to enable students to comprehensively use the knowledge they have learned, discover, propose, analyze and solve practical problems, and exercise practice An important part of ability is the specific training and inspection process of students' ability in actual scenarios. With the rapid development of science and technology, today's computer applications can be said to be everywhere in life.
I encountered many problems during the course design process. Through online inquiries and the enthusiastic help of my classmates, I finally completed the course design successfully. Among them, I fully understand the object-oriented characteristics of Java, and realize the difference between Java and C\C++ language. Only by doing more and writing programs frequently, can we discover our learning defects and our own shortcomings, and solve these problems in practice, and continuously improve our ability to transform knowledge. Through the design of this course, I understand that the combination of theory and practice is very important. Simple theoretical knowledge is far from enough. Only by combining the acquired theoretical knowledge with practice and drawing conclusions from theory can we truly serve the society. Develop my practical skills and abilities. Most of the functions of the program written this time are realized by calling the methods and classes in each package, which also allows me to fully understand the relationship between packages and classes.
Since the program I wrote this time is the first time I write it in Java, I will encounter many small problems, such as: how to save the input number and the next number for addition, subtraction, multiplication, and division. This course is designed to give us a better understanding of the graphical user interface in Java and how it is programmed. In the process of completing the project, I consulted a lot of materials about Java language development, constantly enriched myself, learned a lot of knowledge that I hadn't learned before, and gained a lot. The design of the Java calculator enables us to have a deeper understanding of the courses we have learned, so that the knowledge has been consolidated and improved.
In the future, I will continue to work hard; I believe that as long as you have confidence and perseverance, you will never be defeated!
full source code

package util;
import java.awt.*;

public class Const {
    public static final int FRAME_W = 300;//得到窗体中心点
    public static final int FRAME_H = 300;
    public static final int SCREEN_W = Toolkit.getDefaultToolkit().getScreenSize().width;
    public static final int SCREEN_H = Toolkit.getDefaultToolkit().getScreenSize().height;

    public static final int Frame_X = (SCREEN_W-FRAME_W)/2;
    public static final int Frame_Y = (SCREEN_H-FRAME_H)/2;

    public static final String TITLE = "计算器";
}

package start;
import javax.swing.*;
import util.Const;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class calculator extends JFrame implements ActionListener{
    /**********************北面的控件***********************/
    private JPanel jp_north = new JPanel();
    private JTextField input_text = new JTextField();
    private JButton c_Btn = new JButton("Clear");
     /**********************中间的控件***********************/
     private JPanel jp_center = new JPanel();
     public calculator() throws HeadlessException{//显示窗体
        this.init();
        this.addNorthComponent();
        this.addCenterButton();
    }
    //初始化的方法
    public void init(){
        this.setTitle(Const.TITLE);
        this.setSize(Const.FRAME_W, Const.FRAME_H);
        this.setLayout(new BorderLayout());
        this.setResizable(false);
        this.setLocation(Const.Frame_X,Const.Frame_Y);//设置框架在屏幕的位置
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭键
    }
    //添加北面的控件
    public void addNorthComponent(){
        this.input_text.setPreferredSize(new Dimension(200,30));//设置文本框大小
        jp_north.add(input_text);//加文本框

        this.c_Btn.setForeground(Color.RED);//设置按钮颜色
        jp_north.add(c_Btn);//加按钮
        c_Btn.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                input_text.setText("");
            }
        });

        this.add(jp_north,BorderLayout.NORTH);//将面板加到框架北侧
    }
    //添加中间按钮
    public void addCenterButton(){
        String btn_text = "123+456-789*0.=/";
        String regex = "[\\+\\-*/.=]";//正则表达式
        this.jp_center.setLayout(new GridLayout(4,4));//4*4的布局
        for(int i=0;i<16;i++){//在面板中加按钮
            String tmp  = btn_text.substring(i,i+1);
            JButton btn = new JButton();
            btn.setText(tmp);//给按钮加文字
            if(tmp.matches(regex)){//如果正则匹配
                    btn.setFont(new Font("粗体",Font.BOLD,20));
                    btn.setForeground(Color.RED);
                }
            btn.addActionListener(this);//添加按钮监听器
            jp_center.add(btn);
        }
        this.add(jp_center,BorderLayout.CENTER);//将面板加载框架布局的中间位置
    }
    private String firstInput = null;
    private String operator = null;
    //给按钮添加监听事件
    public void actionPerformed(ActionEvent e){
        String clickStr = e.getActionCommand();
        if(".0123456789".indexOf(clickStr)!=-1){//数字输入
            this.input_text.setText(input_text.getText() + clickStr);
            this.input_text.setHorizontalAlignment(JTextField.RIGHT);
        }
        else if(clickStr.matches("[\\+\\-*/]{1}")){//运算符输入
            operator = clickStr;
            firstInput = this.input_text.getText();
            this.input_text.setText("");
        }
        else if(clickStr.equals("=")){//等号输入
            Double a = Double.valueOf(firstInput);
            Double b = Double.valueOf(this.input_text.getText());
            Double res = null;
            switch (operator){//运算主体
                case "+":
                res = a + b;
                break;
                case "-":
                res = a - b;
                break;
                case "*":
                res = a * b;
                break;
                case "/":
                if(b!=0){
                    res = a/b;
                }
                else{
                    this.input_text.setText("除数不能为0!请清空!");
                }
                break;
            }
            this.input_text.setText(res.toString());
        }
    }

    //主方法
    public static void main(String[] args) {
        calculator Calculator = new calculator();
        Calculator.setVisible(true);
    }

}

Guess you like

Origin blog.csdn.net/qq_57150526/article/details/125601055