Catalog
Preface
This calculation task is based on the first web calculator, which separates the front-end and back-end while ensuring the first function, improving the practicality of the calculator. The front-end still uses HTML, CSS, and Javascript languages, while the back-end is implemented using PHP and MySql. It can not only perform basic addition, subtraction, multiplication, and division operations, but also complex sum of squares root operations, as well as cube and open cube operations.
Some ID information:
The Link Your Class | https://bbs.csdn.net/forums/ssynkqtd-04?typeId=5171414 |
---|---|
The Link of Requirement of This Assignment | https://bbs.csdn.net/topics/617378696 |
GitHub repository | https://github.com/Adonlgd/WebCalculator |
The Aim of This Assignment | Back-end separation calculator programming |
MU STU ID and FZU STU ID | MUID:21124442_FZUID:832102109 |
Ⅰ 、PSP form
Personal Software Process Stages | Estimated Time(minutes) | Actual Time(minutes) |
---|---|---|
Planning | ||
• Estimate | 20 | 30 |
Development | ||
• Analysis | 30 | 20 |
• Design Spec | 30 | 20 |
• Design Review | 20 | 20 |
• Coding Standard | 45 | 30 |
• Design | 15 | 15 |
• Coding | 120 | 200 |
• Code Review | 70 | 30 |
• Test | 20 | 20 |
Reporting | ||
• Test Repor | 20 | 20 |
• Size Measurement | 30 | 30 |
• Postmortem & Process Improvement Plan | 30 | 30 |
Sum | 450 | 465 |
Ⅱ、Problem-solving Ideas
1.Determine code language
The topic is to create a Back-end separation calculator. After understanding these languages, I decided to use the assignment1’s calculator based on HTML, CSS, and JavaScript languages, and then connect it to the MySql database. I decied to use PHP because PHP is mainly used for website development, and many websites are developed using PHP. Developing dynamic pages using PHP is more efficient and faster than other programming languages. PHP can also execute compiled code, making the code run faster.
2.Flow Chart
3. UI Design
Ⅲ、Code description
1.HTML file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Web Calculator</title>
<link rel="stylesheet" type="text/css" href="file.css">
<script type="text/javascript" src="test1.js"></script>
</head>
<body onload="init()">
<div class="div4">
<h1 align="center">
<font face="楷体">Web Calculator</font>
</h1>
</div>
<div class="div1">
<div class="div2">
<input type="text" id="Text1" class="text1" >
</div>
<div class="div3">
<input type="button" value="C" class="">
<input type="button" value="<-" class="">
<input type="button" value="+/-" class="">
<input type="button" value="/" class="">
<input type="button" value="1" class="">
<input type="button" value="2" class="">
<input type="button" value="3" class="">
<input type="button" value="*" class="">
<input type="button" value="4" class="">
<input type="button" value="5" class="">
<input type="button" value="6" class="">
<input type="button" value="-" class="">
<input type="button" value="7" class="">
<input type="button" value="8" class="">
<input type="button" value="9" class="">
<input type="button" value="+" class="">
<input type="button" value="0" class="">
<input type="button" value="." class="">
<input type="button" value="摸鱼" id="readhistory">
<input type="button" value="=" class="">
<input type="button" value="x²" class="">
<input type="button" value="x³" class="">
<input type="button" value="√" class="">
<input type="button" value="∛" class="">
</div>
</div>
</body>
</html>
It can be seen that due to the use of CSS file assistance, the entire HTML code is not particularly lengthy and very easy to read.
2. CSS file
.div1{
width: 400px;
height: 550px;
top: 150px;
left: 600px;
position: absolute;
border-radius: 10px;
background-image: url(2.jpeg);
}
.div2{
width: 350px;
height: 80px;
position: relative;
left: 20px;
top: 42px;
}
.text1{
width: 350px;
height: 60px;
font-size: large;
text-align: right;
background-color: white;
}
.div3{
width: 340px;
height: 350px;
position: relative;
left: 30px;
top: 70px;
border-radius: 10px;
background-color: darkblue;
}
.div4{
width: 400px;
height: 100px;
top: 50px;
left: 600px;
position: absolute;
border-radius: 10px;
background-color: cyan;
}
input[type="button"]{
height: 40px;
width: 60px;
margin: 8px;
margin-left: 13px;
border-radius: 10px;
background: goldenrod;
}
input[type="button"]:hover{
background-color: cornflowerblue;
border: 2px solid;
}
3. JavaScript file
/*Place the initialized content in JS and store the style content
Put it in CSS, and only write basic HTML content such as class and value in HTML*/
function init(){
initLabel();
fun();
Link();
}
/*Initialize the content of the text box*/
function initLabel(){
let value=document.getElementById("Text1");
value.value=0;
value.disabled="disabled";
}
//Button Add Function
function fun(){
let getText=document.getElementById("Text1");
let nums=document.getElementsByTagName("input");
let numFirst,symbol;
for (let i=0;i<nums.length;i++){
nums[i].onclick=function (){ //isNaNIf this function judge if it is a number, it returns false, and if it is not a number, it returns true
if (!isNaN(this.value)){
if (isNull(getText.value))
getText.value=this.value;
else
getText.value=getText.value+this.value;
}
else{/*Non numeric operations*/
let button_info=this.value;
switch (button_info){
//Non operator operations
case "C":
getText.value=0;
break;
case "<-":
getText.value=myBack(getText.value);
break;
case "+/-":
//Once clicked, it becomes a symbol, and once more clicked, it becomes a positive sign
getText.value=mySign(getText.value);
break;
case ".":
//The decimal point can only be clicked once
getText.value=point_fun(getText.value);
break;
//Complex operations
case "x²":
numFirst=getText.value*1;
getText.value=numFirst*numFirst;
break;
case "x³":
numFirst=getText.value*1;
getText.value=numFirst*numFirst*numFirst;
break;
case "√":
numFirst=getText.value*1;
getText.value=Math.sqrt(numFirst);
break;
case "∛":
numFirst=getText.value*1;
getText.value=Math.cbrt(numFirst);
break;
//Simple operations
case "/":
numFirst=getText.value*1;
getText.value=0;
symbol="/"
break;
case "*":
numFirst=getText.value*1;
getText.value=0;
symbol="*"
break;
case "-":
numFirst=getText.value*1;
getText.value=0;
symbol="-"
break;
case "+":
numFirst=getText.value*1;
getText.value=0;
symbol="+"
break;
case "+":
numFirst=getText.value*1;
getText.value=0;
symbol="+"
break;
case "Ans":
getText.value="3*7=21 68*889=60452";
break;
case "=":
switch (symbol){
//ParseInt() cannot be used to convert a string to a number below, as if there are decimals, they will be automatically converted to integers
//Method for converting strings to numbers:
//1. Value * 1 implementation
//2. ParseInt() implementation
//3. Number() implementation
case "+":
getText.value=numFirst+Number(getText.value);
break;
case "-":
getText.value=numFirst-Number(getText.value);
break;
case "*":
getText.value=numFirst*Number(getText.value);
break;
case "/":
if (!isNull(getText.value))
getText.value=numFirst/Number(getText.value);
else{
getText.value=0;
numFirst=0;
alert("Divider cannot be 0 or empty")
}
break;
}
break;
}
}
}
}
}
/functions
//Implement sign function
function mySign(n){
return Number(n)*(-1);
}
//Realize the function of the exit key
function myBack(n){
n=n.substr(0,n.length-1);
if (isNull(n))
n=0;
return n;
}
//Implement decimal point function
function point_fun(n){
//indexOf() indicates whether this symbol exists, returns the position if it exists, and returns -1 if it does not exist
if (n.indexOf(".")==-1)
n=n+".";
return n;
}
//Operation to determine whether the text box is empty or 0
function isNull(num){
return (num=="0"||num.length==0)?true:false;
}
document.getElementById('readhistory').onclick = function () {
var Ans = document.getElementById("result2");
var result = document.getElementById("result1");
var contentAsString = String(Ans.textContent);
result.innerHTML = Ans.innerHTML;
var xhr = new XMLHttpRequest();
// 配置请求,使用GET请求方式,请求的URL为后端PHP文件的路径
xhr.open("GET", "backend.php", true);
//发送请求
xhr.send();
// 设置回调函数,处理响应
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// 如果请求成功完成,处理后端返回的JSON数据
var response = JSON.parse(xhr.responseText);
for (var i = 0; i < response.length; i++) {
var recordId = "hist" + (i + 1);
var recordDiv = document.getElementById(recordId);
recordDiv.innerHTML = response[i];
}
}
};
}
function calculateExpression(expression) {
let index = 0;
function throwError(message) {
throw new Error(message);
}
function parseNumber() {
let start = index;
if (expression[index] === '-') {
index++;
}
while (/\d|\./.test(expression[index])) {
index++;
}
return parseFloat(expression.slice(start, index));
}
}
document.getElementById('save').onclick = function () {
var result = document.getElementById("result1");
var result1 = document.getElementById("result2");
finalResult = calculateExpression(result.innerHTML);
result1.innerHTML = finalResult;
var str1 = document.getElementById('result1').innerHTML;
var str2 = document.getElementById('result2').innerHTML;
var xhr = new XMLHttpRequest();
var url = `history.php?result1=${str1}&result2=${str2}`;
xhr.open('get', url, true)
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log(xhr.response);
}
}
}
result.innerHTML = "";
}
function res() {
var result = document.getElementById("result1");
var result1 = document.getElementById("result2");
console.log(typeof result.innerHTML)
finalResult = calculateExpression(result.innerHTML);
result1.innerHTML = finalResult;
result.innerHTML = "";
}
function del() {
var result = document.getElementById("result1");
var len = result.innerHTML.length;
result.innerHTML = result.innerHTML.substr(0, len - 1);
}
function clear1() {
var result = document.getElementById("result1");
result.innerHTML = "";
var result1 = document.getElementById("result2");
result1.innerHTML = "";
for (var i = 0; i < 10; i++) {
var hist = "hist" + (i + 1);
var hist_clear = document.getElementById(hist);
hist_clear.innerHTML = "";
}
}
4. PHP file
RECEIVE AND SEND
<?php
// connect
$con = mysqli_connect('localhost','root','lgd000','history_list');
if($con){
//set code format
mysqli_query($con,'set names utf8');
$sql = "select expression from history_table order by no desc limit 10";
$result = $con->query($sql);
// change to array
$data = [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row['expression'];
}
}
$con->close();
// return json
echo json_encode($data);
}else{
echo 'file to vonnect';
}
?>
<?php
$expression=$_GET['result1'];
$res=$_GET['result2'];
$re_exp = str_replace(" ", "+", $expression);
$final_exp=$re_exp."=".$res;
echo "$final_exp";
$con = mysqli_connect('localhost','root','lgd000','history_list');
if($con){
//set code format
mysqli_query($con,'set names utf8');
$sql = "insert into history_table(expression,result) values('$final_exp','$res')";
$result=mysqli_query($con,$sql);
}else{
echo 'fail to connect';
}
?>
Ⅳ、Vedio demo
1. +,-,*,/
2.±, <- , x² ,x³ ,√ ,∛
3.history read
when we calculate 3*7=21, the express and result will be saved into the database, and when we click the “Ans”, the web can get the array and display it on the textscreen.
Then we continue to calculate, the next express and result will also be saved in the database.
Ⅴ、Summary
In this assignment, I designed a Back-end separation calculator. The calculator program is based on HTML, CSS, Javascript PHP and MySql. Calculators can perform basic addition, subtraction, multiplication, and division operations, as well as square sum and square root operations, as well as cube and open cube operations. More importantly, calculators can achieve read history functiont through the connection with database. The website to be redirected can be customized in the code according to the user’s preferences.