Second Assignment------Calculator (Advanced)

Introduction:

Below is the basic link table for this project:

The Link Your Classhttps://bbs.csdn.net/forums/ssynkqtd-04
Link of Requirement of This Assignmenthttps://bbs.csdn.net/topics/617332156
Objectives of This AssignmentTo improve the exist calculator(More calculation functions and add history,create connection between database and the compiler.)
MU STU ID and FZU STU ID<832102223_21126348>

Github Responsiry: Github Front-End And Back-End Code Link

PSP Table:

The PSP table of the project are as follows:

Personal Software Process StagesEstimated Time(minutes)Actual Time(minutes)
Planning4540
Estimate4540
Development610665
Analysis10080
Design Spec4040
Design Review2525
Coding Standard2025
Design4550
Coding300350
Code Review3045
Test5050
Reporting4040
Test Report2025
Size Measurement2015
Postmortem &Process Improvement Plan2520
Sum720765

The Calculator Display:

Test_Video

在这里插入图片描述

Design Ideas:

Ideas of Implementation

In this project, we need to implement the front-end and back-end links. In order to realize that, we need to record the button we click. Then, generate the equation in
the database. Once the connection has been set up, we will see the latest result and the recent ten records(equations) from the windows.
Basic Operation:
If the number has been clicked, the number will be recorded.
If the operators except for “=” have been clicked, the operator will be recorded.
If the “=” has been clicked, the result value and “=” will be record and the whole equation will be transferred to the back-end MySql database, and have a
corresponding ID for this equation.
If the “ans” has been clicked, the latest value will be shown on the column.
If the “history” has been clicked, the recent ten records will be shown on another window.

Flow Chart:

The flow-chart of the project is shown as follows:

在这里插入图片描述

Coding Explanation:

In this project I use Java to construct a calculator and also use Java to make the connection between front and back end.

Front End:

Below is the Const class for this project:
This is the class which is used for containing constant values of this calculator.

import java.awt.Toolkit;

public class Const {
	public static final int FRAME_W = 300;
	public static final int FRAME_H = 400;
	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";
}

The main class of the calculator is shown as follows:


public class Calculator extends JFrame implements ActionListener{
	//North component:
	private JPanel jp_north = new JPanel();
	private JTextField input_text = new JTextField();
	private JButton c_Button = new JButton("C");
	
	//Central component:
	private JPanel jp_centre = new JPanel();
	String content = "";
	static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";  
    static final String DB_URL = "jdbc:mysql://localhost:3306/dbtest1?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";//This is the database where it contains the wanted table
   // The USER ID and PASSPORT:
   static final String USER = "root";
   static final String PASS = "ycr.020910";
   //Written by Chengrui Yuan
   //Date:2023.10.21
   
	public Calculator () throws HeadlessException{
		this.init();
		this.addNorthComponent();
		this.addCentreButton();
	}
	//Doing initialization:
	public void init() {
		this.setTitle(Const.TITLE);
		this.setSize(Const.FRAME_H,Const.FRAME_W);
		this.setLayout(new BorderLayout());
		this.setResizable(false);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	//Adding north component:
	public void addNorthComponent() {
		//Setting basic attribute of this calculator.
		this.input_text.setPreferredSize(new Dimension(300,50));
		jp_north.add(input_text);
		this.c_Button.setForeground(Color.black);
		jp_north.add(c_Button);
		c_Button.setFont(new Font("粗体",Font.BOLD,16));
		c_Button.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				input_text.setText("");
				content = "";
			}
		});
		this.add(jp_north,BorderLayout.NORTH);
	}
	//Adding central component:
	public void addCentreButton(){
		String [] txt = {"1","2","3","+","ans","history","4","5","6","-","log","sin","7","8","9","*","^","cos","0",".","=","/","%","tan"};
		String reg = "[\\+\\-\\*\\/\\.\\=\\^\\%]";
		this.jp_centre.setLayout(new GridLayout(4,6));
		for (int i = 0;i<24;i++) {
			String temp = txt[i];
			JButton button = new JButton();
			button.setText(temp);
			if(temp.matches(reg)) {
				button.setFont(new Font("粗体",Font.BOLD,18));
				button.setForeground(Color.BLACK);
			}else{
				button.setFont(new Font("粗体",Font.BOLD,18));
				button.setForeground(Color.GRAY);
			}
			button.addActionListener(this);
			jp_centre.add(button);
		}
		this.add(jp_centre,BorderLayout.CENTER);
	}
	
	//Main function:
	public static void main(String[] args) {
		   Calculator calculator = new Calculator();
		   calculator.setVisible(true);
	}

	private String preInput = null;
	private String operator = null; 
	
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		String clickStr = e.getActionCommand();
		if(".0123456789".indexOf(clickStr) != -1) {
			//if enter the numbers on the calculator
			this.input_text.setText(input_text.getText() + clickStr);
			this.input_text.setHorizontalAlignment(JTextField.RIGHT);
			//Record the input into a string.
			content+=clickStr;
		}else if(clickStr.matches("[\\+\\-\\*\\/\\^\\%]")||clickStr.matches("log")|| clickStr.matches("sin") || clickStr.matches("cos") || clickStr.matches("tan")) {
			//if click the operator.
			operator = clickStr;
			preInput = this.input_text.getText();
			this.input_text.setText("");
			//Record the operator into the string.
			content+=clickStr;
		}
		else if(clickStr.equals("=")) {
			//if the clicked button is "=";
			content += clickStr;
			 Double preValue = 0.0;
	         Double latValue = 0.0;
	            if (preInput.matches("-?\\d+(\\.\\d+)?")){
	                preValue = Double.valueOf(preInput);
	            }
	            if (this.input_text.getText().matches("-?\\d+(\\.\\d+)?")) {
	                latValue = Double.valueOf(this.input_text.getText());
	            }
	        Double result = null;
			boolean flag = true;
			String error = null;
			switch(operator) {
			//doing calculation:
			case "+":
					result = preValue + latValue;
					break;
			case "-":
					result = preValue - latValue;
					break;
			case "*":
					result = preValue * latValue;
					break;
			case "/":
					if(latValue != 0) {
						result = preValue/latValue;
						break;
					}else {
						flag = false;
						error = "Invalid Operation!";
						break;
					}
			case"^":
					result = Math.pow(preValue, latValue);
					break;
			case"%":
				if(latValue != 0) {
					result = preValue%latValue;
					break;
				}else {
					flag = false;
					error = "Invalid Operation!";
					break;
				}
			 case"log":
					result = Math.log(preValue)/Math.log(latValue);
					break;
			 case "sin":
                 	BigDecimal   SINresult   =   new   BigDecimal(Math.sin(Math.toRadians(latValue)));
                 	result = SINresult.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
                 	break;
             case "cos":
                 	BigDecimal   COSresult   =   new   BigDecimal(Math.cos(Math.toRadians(latValue)));
                 	result = COSresult.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
                 	break;
             case "tan":
                 	BigDecimal   TANresult   =   new   BigDecimal(Math.tan(Math.toRadians(latValue)));
                 	result = TANresult.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
                 	break;
					}
			content += result;
			
			//Display the result into the given column.
			if(flag)
				this.input_text.setText(result.toString());
			else
				this.input_text.setText(error);

In this part, I construct a window to show the buttons and the layout of the characters(operators and numbers). Then I write codes to realize the functions of plus, minus, multiplication, division, getting remainder, power operation, logarithm operation and trigonometric functions. Also, in this calculator we can see ans and history button on it, which are connections between the front end and the back end(Show latest answer(ans) and ten recent answer(history)).

Back End:

First, I created a table, which is in the existed database dbtest1 in the Navicat:
在这里插入图片描述

在这里插入图片描述

Next, I construct the connection between the MySql database and the java project, to record the equations and results into the database,which is convenient for us to invoke the data from the database.
The front-end will communicate with the server and send the command and write the recorded data to the database.
Then, when the back-end database receive the data, the database will check the sentences which are satisfied with the requirements. Then it will deal with the information and then send the sentences back to the front-end to display.


			 try {
	                Class.forName(JDBC_DRIVER);
	                Connection conn = DriverManager.getConnection(DB_URL,USER, PASS);    //construct the connection to MySQL database
	                String histContent = "'" + content + "'";           //storing the previous operation
	                int countNum = 1;
	                String mySql = "";                              //initialize the MySql sentence
	                Statement statement = conn.createStatement();
	                mySql = "update calculator_history set CONTENT = " + result + " where ID = " + countNum;
	                statement.executeUpdate(mySql);                 //execute MySql sentence to update the latest result on first row in database
	                countNum++;
	                mySql = "select ID,CONTENT from calculator_history";
	                Statement stmt = conn.createStatement();
	                ResultSet res = stmt.executeQuery(mySql);           //Get messages from database and record in res
	                res.next();                                         //Ignore the first row and get the latest answer from database.
	                mySql = "update calculator_history set CONTENT = " + histContent + " where ID = " + countNum;           //Get the previous operations to following rows in database
	                while (res.next()) {                         		//if there are exist next row in database
	                    histContent = "'" + res.getString("CONTENT") + "'";          //remember the current row for it will be rewrote by following code
	                    statement.executeUpdate(mySql);
	                    countNum++;
	                    mySql = "update calculator_history set CONTENT = " + histContent + " where ID = " + countNum;
	                }
	                //release obtained resources
	                statement.close();
	                stmt.close();
	                conn.close();
	            } catch (SQLException ex) {
	                throw new RuntimeException(ex);
	            } catch (ClassNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}


Then, I set up the connection between MySql and eclipse, to realise the two functions: Check the previous one operation and the previous ten operations through buttton “ans” and “history”.

else if (clickStr.equals("ans")) {
            try {
                Class.forName(JDBC_DRIVER);
                Connection connection = DriverManager.getConnection(DB_URL,USER,PASS);
                Statement statement = connection.createStatement();
                String mySql = "select ID,CONTENT from calculator_history";
                ResultSet res = statement.executeQuery(mySql);
                Statement stmt = connection.createStatement();
                res.next();
                /*if (!res.next()) {  //ResultSet 为空 
                	}else{//ResultSet 不为空
                	}*/
                //obtain the first row in content column of database.
                String preResult = res.getString("CONTENT"); 
                
                //print the message obtained in display window.
                this.input_text.setText(preResult);                        
                res.close();
                stmt.close();
                connection.close();
            } catch (SQLException e1) {
                e1.printStackTrace();
            } catch (ClassNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
        }
			
			else if(clickStr.equals("history")) {
				//initialize a string to conserve the information from database.
				String[] hisContent = new String[10];     
	            //Driver registration.
	            try {
	                Class.forName(JDBC_DRIVER);
	                Connection conn = DriverManager.getConnection(DB_URL,USER, PASS);
	                Statement statement = conn.createStatement();
	                String mySql = "select ID,CONTENT from calculator_history";
	                ResultSet res = statement.executeQuery(mySql);
	                Statement stmt = conn.createStatement();
	                int countNum = 0;
	                //skip to second row in database
	                res.next();                               
	                while (res.next()) {
	                	//receive the message from database and store them in String array for examining.
	                    hisContent[countNum] = res.getString("CONTENT");          
	                    countNum++;
	                }
	                res.close();
	                stmt.close();
	                conn.close();

	            } catch (SQLException e1) {
	                e1.printStackTrace();
	            } catch (ClassNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}


Finally, creating a new window to display the ten equations from the database at the back end.

//construct another window in java to show history operations
	    					JFrame j_frame = new JFrame();
	    		            j_frame.setTitle("HISTORY_CONTENT");
	    		            JPanel p = new JPanel();
	    		            JTextField Text[]= new JTextField[10];
	    		            for(int i = 0; i < 10; i++) {
	    		                Text[i] = new JTextField();
	    		                Text[i].setEditable(false);
	    		                Text[i].setHorizontalAlignment(JTextField.CENTER);
	    		                Text[i].setPreferredSize(new Dimension(250,150));
	    		              //set the blocks in window to represent the information retain in String array
	    		                Text[i].setText(hisContent[i]);                  
	    		                Font font=new Font("",Font.BOLD,35);
	    		                Text[i].setFont(font);
	    		                p.add(Text[i],BorderLayout.NORTH);
	    		            }
	    		            j_frame.add(p);
	    		            j_frame.setBounds(700, 300, 600, 700);
	    		            j_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    		            j_frame.setVisible(true);


Summary:

In this project, I learned a lot about how to creating a calculator and invoke the history operation through the database. In this project I connect the MySql and Eclipse to develop this project, which is very unfamiliar and challenging for me. Finally, I realize the front-end and back-end connection and can realize the basic function of a calculator. This calculator can adjust some basic environments of doing simple calculations, and it can also display some basic elementary functions like exponential functions, logarithm functions and trigonometric functions and so on. But this calculator is still incomplete and still have many shortages, which need more time to do some modification.
I gained a lot in this project, and I believe I still have many aspects to improve as well.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值