Second assignment-- Back-end separation calculator programming

Software Engineering Practice Second Assignment——Back-end separation calculator programming

Course for This AssignmentSoftware Engineering
Assignment Requirementshttps://bbs.csdn.net/topics/617378696
Objectives of This AssignmentThe connection of front-end and back-end
Other Referenceshttps://b23.tv/QJmOz4u

1 Introduction

  1. Basic calculator functions
    Function 1: addition, subtraction, multiplication, division, remainder
    Basic +, -, *, /, %,operations, requiring the correct order of operations, the correct result, and store the input string and the result in a back-end database
    Function 2: Read history
    Can use the ans button to return the previous calculation result, and view the history to read the last ten string formula and the corresponding calculation result, must be read from the back-end database, can not use the cache.
  2. Extended function: Scientific calculator
    (1)Calculate radical sign, trigonometric function, log, scientific notation
    (2)Implement bracket computation
    (3)Better looking UI interface

2 PSP form

Personal Software Process StagesEstimated Time(minutes)Actual Time(minutes)
Planning
• Estimate4050
Development
• Analysis3035
• Design Spec2040
• Design Review1020
• Coding Standard4050
• Design4550
• Coding350300
• Code Review4045
• Test3045
Reporting
• Test Repor3030
• Size Measurement3030
• Postmortem & Process Improvement Plan3030
Sum695725

3 Description of problem-solving ideas

In the last blog, I used Front-end page visualization mainly consists of HTML, CSS, JavaScript. These components work together to realize the display of web content, the definition of style and the presentation of web interaction. In this task, HTML is responsible for building the page structure of the calculator, CSS is responsible for styling the appearance of the calculator, and JavaScript provides the interactive functions and calculation logic of the calculator, so as to realize the design and development of a simple visual calculator.
This episode introduces the need for a back-end database where I want to transfer data to IntelliJ IDEA and use Node.js on the front end to process and render the data.

4 Design and implementation process

HTML section:
I used the HTML markup language to create a page structure containing the calculator interface.
At <head> tag. A style sheet file called style.css is introduced in the tag to define the appearance style of the calculator.
At <body> Tag, I creates a calculator container <div> with a specific style class name that contains the display <input> And a series of buttons.

CSS section:
I used CSS stylesheets to style the look of the calculator.
By styling the.Calculator class, I arranged the internal elements in a grid layout and set other style properties such as color, background, and so on.

JavaScript section:
I’ve defined some functions in blocks of JavaScript code to handle the operations and logic of the calculator.
The append(value) function appends the value of the button clicked by the user to the display.
The clearDisplay() function is used to clear the display.
The calculate() function is used to calculate the result of an expression and display it on the screen, while inserting the expression and result into the history of the database.
The calculateSquareRoot(), calculateSine(), calculateCosine(), and calculateLogarithm() functions are used to compute the results of the square root, sine, cosine, and logarithm, respectively, and are displayed on the screen.
The insertHistory(expression, result) function is used to insert expressions and results into the history table in the database.

Back-end: Node.js Express framework:
I create an Express application called server.
The route /history of a GET request is defined. When a client initiates a request for this route, the last 10 history records are queried from the MySQL database and the result is returned to the client as a JSON response.

IntelliJ IDEA Database:
I created a MySQL connection pool (pool) in the code, using the pool.query() method to execute the SQL statement and handle the results returned.

The above logic loops until the user finishes the operation.
flow chart
key step flow chart

5 Code description

HTML code

<!DOCTYPE html>
<html>
<head>
  <title>Calculator</title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
  <div class="calculator">
    <div id="history-container" style="display: none;">
        <h3>History</h3>
        <ul id="history-list"></ul>
      </div>
    
    <input class="value" type="text" id="display" readonly>
      <button class="clr" onclick="clearDisplay().value">AC</button>
      <button onclick="deleteLastCharacter().value">&larr;</button>
      <button onclick="append('/').value">/</button>
      <button onclick="append('7').value">7</button>
      <button onclick="append('8').value">8</button>
      <button onclick="append('9').value">9</button>
      <button onclick="append('*').value">*</button>
      <button onclick="append('4').value">4</button>
      <button onclick="append('5').value">5</button>
      <button onclick="append('6').value">6</button>
      <button onclick="append('+').value">+</button>
      <button onclick="append('1').value">1</button>
      <button onclick="append('2').value">2</button>
      <button onclick="append('3').value">3</button>
      <button onclick="append('-').value">-</button>
      <button class="zero" onclick="append('0').value">0</button>
      <button onclick="append('.').value">.</button>
      <button class="equal" onclick="calculate().value">=</button>
      <button onclick="calculateSine()">sin</button>
      <button onclick="calculateCosine()">cos</button>
      <button onclick="calculateTan()">tan</button>
      <button onclick="calculateLogarithm().value">log</button>
      <button class="an" onclick="append('ans').value">ans</button> 
      <button onclick="calculateSquareRoot().value"></button>
      <div> <button class="history" onclick="insertHistory()">History</button></div>
    </div>
  </div>
  <script src="script.js"></script>
  <script src="server.js"></script>
</body>
</html>


CSS code

*
*
{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins ' , sans-serif;
}
body{
    display: flex;
    justify-content: center;
    align-items : center;
    min-height: 100vh;
    background: #7a929e;

 
}

.calculator {
  position: relative;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  width: 400px; 
  height: 425px;
}

  .calculator .value {
    grid-column: 1 / span 4;
    height: 80px;
    text-align: right;
    padding: 15px;
    font-size: 15px;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(3, 3, 3, 0.133);
  }
  
  .calculator button {
    display: grid;
    width: 100%;
    height: 50px;
    margin: auto;
    color: #fff;
    background-color: #1d5772;
    place-items: center;
    border: 1px solid rgba(0, 0, 0, 0.1);
  }
  
  .calculator button:active {
    color: #111;
    background-color: #649e9b;
  }
  
  .calculator button.clr {
    grid-column: 1 / span 2;
    width: 100%;;
  }
  
  .calculator button.zero {
    grid-column: 1 / span 2;
    width: 100%;
  }
  
  .calculator button.an {
    grid-column: 1 / span 2;
    width: 100%;
  }
  
  .calculator button.equal {
    background-color: #3bcbd5;
  }


JS code

let expression = '';

function append(value) {
  if (value === 'ans') {
    expression += ans; // 如果是'ans',将上一次计算的结果追加到表达式中
  } else {
    expression += value;
  }
  document.getElementById('display').value = expression;
}

function clearDisplay() {
  expression = '';
  document.getElementById('display').value = '';
}

function calculate() {
  const result = eval(expression);
  document.getElementById('display').value = result;
  //Insert history records into the database
  insertHistory(expression, result);
  expression = '';
}

function insertHistory(expression, result) {
  // Perform the database insert operation
  const query = `INSERT INTO history_table (expression, result) VALUES ('${expression}', '${result}')`;
  //pool.query(query, (error, results) => {
    if (error) {
      console.error('Error inserting history:', error);
    }
  };
//}

function calculateSquareRoot() {
    const operand = parseFloat(expression);
    const result = Math.sqrt(operand);
    document.getElementById('display').value = result;
    expression = '';
  }
  
  function calculateSine() {
    const operand = parseFloat(expression);
    const angleInRadians = operand * Math.PI / 180; // Convert angles to radians
    const result = Math.sin(angleInRadians);
    document.getElementById('display').value = result.toFixed(4);
    expression = '';
  }
  
  function calculateCosine() {
    const operand = parseFloat(expression);
    const angleInRadians = operand * Math.PI / 180; 
    const result = Math.cos(angleInRadians);
    document.getElementById('display').value = result.toFixed(4);
    expression = '';
  }
  
  function calculateLogarithm() {
    const operand = parseFloat(expression);
    const result = Math.log10(operand);
    document.getElementById('display').value = result;
    expression = '';
  }

Node.js

const express = require('express');
const server = express();
const app = express();
const port = 3306;

var mysql = require('mysql');

const pool = mysql.createPool({
connectionLimit:10,
host: 'localhost',
user: 'mysql.infoschema',
password: '123456789',
database: 'history_table'
});

server.get('/history', (req, res) => {
var query = 'SELECT * FROM history_table';
 pool.query('SELECT * FROM history_table ORDER BY id DESC LIMIT 10', (error, results) => {
  if (error) {
    console.error('Error fetching history:', error);
    res.sendStatus(500);
  } else {
    res.json(results);
  }
});
});

app.get('/history', (req, res) => {
  const query = 'SELECT * FROM history_table ORDER BY id DESC LIMIT 10';
  pool.query(query, (error, results) => {
    if (error) {
      console.error('Error fetching history:', error);
      res.sendStatus(500);
    } else {
      res.json(results);
    }
  });
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

6 GitHub link

https://github.com/301lab2

7 Display and description

display
This assignment adds trigonometric function and logarithm function, as well as buttons to view history:history, and return the previous answer answer:ans. These functions are shown in the demonstration video. We can get the following recorded results in the Intellij Idea database:
datahistory
previous data in history_table

8 Conclusion

The second assignment required me to design a calculator by combining the front and back ends. During these weeks of learning, I have mastered the express framework of Node.js, the use of Intellij Idea database and the back-end data integration of MYSQL. It can make them run to achieve the purpose of simple calculation and historical query, and understand the process of the application and response of the whole program in the web page, which makes me have a deeper understanding of web development. I believe that with this progress of continuous learning, I will be able to continuously improve my computer-related skills in the future.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值