简易计算器的实现(JSP)
7JSP实例-jsp版计算器
Wel.jsp
验证失败
users表
6
用户登录系统要求
学习如何在JSP页面间跳转 JSP如何操作数据库 JSP如何显示数据 JSP如何分页
7
连接数据库注意事项
连接数据库三部曲 加载相应的jar包
8
JSP脚本元素
JSP声明(declaration)用来在JSP页面中声明变量和 定义方法。声明是以<%!开头,以%>结束的标签 ,其中可以包含任意数量的合法的Java声明语句
纯JSP技术,不带任何Java Class JSP+Java Class
4
Model1模式的优缺点
表现层和业务逻辑层混合在一起 开发过程中,不利于多人协同开发 不利后期维护
简单,开发速度快 比较合适开发较小的项目
5
Model1模式-纯JSP形式
Login.jsp
登录请求
LoginCl.jsp
小脚本(scriptlet)是嵌入在JSP页面中的Java代码段 。小脚本是以<%开头,以%>结束的标签。 表达式(expression)是以<%=开头,以%>结束的 标签,它作为Java语言表达式的占位符。
9
分页算法
定义四个变量
1. 2. 3.
4.Βιβλιοθήκη int pageSize;//每页显示记录数,用户设置 int pageNow;//希望显示第几页,用户选择 int rowCount;//一共有多少条记录,从数 据库表中查询得到的 int pageCount;//一共有多少页,通过计算 得到
考 计算器
第七讲 Java EE基础入门 JSP版计算器的开发
用java代码写的简易计算器(可以实现基本的加减乘除功能)
⽤java代码写的简易计算器(可以实现基本的加减乘除功能)package A;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import javax.swing.*;public class Calcular3 extends JFrame implements ActionListener,MouseListener{private int m1=0,n=0;//private double m2=0;//运算的数private int flag=0;JFrame f;JPanel p1,p2,p3;JTextField t;JButton b1[]=new JButton[18];String b[]= {"1","2","3","4","5","6","7","8","9","0","清空","退格",".","=","+","-","*","/"};public Calcular3(){f=new JFrame("计算器");t=new JTextField(35);p1=new JPanel();p2=new JPanel();p3=new JPanel();f.setBounds(100, 100, 400, 200);f.add(p1,BorderLayout.NORTH);f.add(p2,BorderLayout.CENTER);f.add(p3,BorderLayout.EAST);p2.setLayout(new GridLayout(5,3));p3.setLayout(new GridLayout(4,1));p1.add(t);for(int i=0;i<14;i++) {b1[i]=new JButton(b[i]);p2.add(b1[i]);b1[i].addActionListener(this);}for(int i=14;i<18;i++) {b1[i]=new JButton(b[i]);p3.add(b1[i]);b1[i].addActionListener(this);}/*for(int i=0;i<18;i++) {b1[i].addActionListener(this);}*/f.setVisible(true);}//实现接⼝的⽅法public void mouseClicked(MouseEvent e) {}public void mousePressed(MouseEvent e) {}public void mouseReleased(MouseEvent e) {}public void mouseEntered(MouseEvent e) {}public void mouseExited(MouseEvent e) {}public void actionPerformed(ActionEvent e) {String str="";int i;for(i=0;i<=9;i++) {if(e.getSource()==b1[i]) {if(i==9) {n=n*10;}else {n=n*10+i+1;}str=String.valueOf(n);//整形n转换成字符串strt.setText(str);//显⽰到⽂本框上}}for(i=14;i<18;i++) {//+、-、*、/if(e.getSource()==b1[i]) {//匹配运算符m1=Integer.parseInt(t.getText());if(flag==15) {m2=m1+m2;}else if(flag==16) {m2=m1-m2;}else if(flag==17) {m2=m1*m2;}else if(flag==18) {m2=m1/m2;}else m2=m1;//若⽆连续的运算符运算,保存当前数据到m2 if(i==14) flag=15;else if(i==15) flag=16;else if(i==16) flag=17;else flag=18;str=String.valueOf(b[i]);t.setText(str);//显⽰到⽂本框上n=0;//还原,记录下次数据break;//找到匹配数据退出循环}}if(e.getSource()==b1[13]) {//=m1=Integer.parseInt(t.getText());if(flag==15) {m2=m2+m1;}else if(flag==16) {m2=m2-m1;}else if(flag==17) {m2=m2*m1;}else if(flag==18) {m2=m2/m1;}else m2=m1;str=String.valueOf(m2);t.setText(str);//显⽰到⽂本框上n=0;//还原,记录下次数据flag=0;//flag还原0,表明没有未处理的运算符}if(e.getSource()==b1[10]) {//各变量变为0 清空m1=0;m2=0;flag=0;n=0;t.setText("0");//显⽰到⽂本框上}if(e.getSource()==b1[11]) {//退格m1=(int)(Double.parseDouble(t.getText())/10);n=m1;str=String.valueOf(m1);t.setText(str);}if(e.getSource()==b1[12]) {//⼩数点m1=Integer.parseInt(t.getText());str=String.valueOf(m1+b[12]);t.setText(str);//显⽰到⽂本框上int j=0;for(i=0;i<=9;i++) {if(e.getSource()==b1[i]) {j++;m2=Math.pow(0.1, j)*Integer.parseInt(b[i]);str=String.valueOf(m1+m2);t.setText(str);//显⽰到⽂本框上}}}}//主函数public static void main(String[] args) {new Calcular3();}}。
JS实现简易计算器的7种方法
JS实现简易计算器的7种⽅法先放图(好吧⽐较挫)⽅法⼀:最容易版<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><title>简易计算器</title><style>body {background-color: #eee;}#calculator {margin: 100px 0 0 150px;}</style></head><body><!-- 简易计算器 --><div id="calculator"><p><input type="text" class="formerInput" value="1" /><span class="sign">+</span><input type="text" class="laterInput" value="1" /><span>=</span><span class="resultOutput">2</span></p><p><input type="button" value="+" onclick="addHandler();" /><input type="button" value="-" onclick="subtractHandler();" /><input type="button" value="×" onclick="multiplyHandler();" /><input type="button" value="÷" onclick="divideHandler();" /></p></div><script>// 获取元素var calculator = document.querySelector('#calculator');var formerInput = calculator.querySelector('.formerInput');var laterInput = calculator.querySelector('.laterInput');var sign = calculator.querySelector('.sign');var resultOutput = calculator.querySelector('.resultOutput');// 加function addHandler() {sign.innerHTML = '+';resultOutput.innerHTML = +formerInput.value + +laterInput.value;}// 减function subtractHandler() {sign.innerHTML = '-';resultOutput.innerHTML = formerInput.value - laterInput.value;}// 乘function multiplyHandler() {sign.innerHTML = '×';resultOutput.innerHTML = formerInput.value * laterInput.value;}// 除function divideHandler() {sign.innerHTML = '÷';resultOutput.innerHTML = formerInput.value / laterInput.value;}</script></body></html>⽅法⼆:结构和⾏为分离<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><title>简易计算器</title>#calculator {margin: 100px 0 0 150px;}</style></head><body><!-- 简易计算器 --><div id="calculator"><p><input type="text" class="formerInput" value="1" /><span class="sign">+</span><input type="text" class="laterInput" value="1" /><span>=</span><span class="resultOutput">2</span></p><p><input type="button" value="+" onclick="addHandler();" /><input type="button" value="-" onclick="subtractHandler();" /><input type="button" value="×" onclick="multiplyHandler();" /><input type="button" value="÷" onclick="divideHandler();" /></p></div><script>// 获取元素var calculator = document.querySelector('#calculator');var formerInput = calculator.querySelector('.formerInput');var laterInput = calculator.querySelector('.laterInput');var sign = calculator.querySelector('.sign');var resultOutput = calculator.querySelector('.resultOutput');var btns = calculator.querySelectorAll('.btn');// 绑定事件// +btns[0].onclick = addHandler;// -btns[1].onclick = subtractHandler;// ×btns[2].onclick = multiplyHandler;// ÷btns[3].onclick = divideHandler;// 加function addHandler() {sign.innerHTML = '+';resultOutput.innerHTML = +formerInput.value + +laterInput.value; }// 减function subtractHandler() {sign.innerHTML = '-';resultOutput.innerHTML = formerInput.value - laterInput.value;}// 乘function multiplyHandler() {sign.innerHTML = '×';resultOutput.innerHTML = formerInput.value * laterInput.value;}// 除function divideHandler() {sign.innerHTML = '÷';resultOutput.innerHTML = formerInput.value / laterInput.value;}</script></body></html>⽅法三:循环绑定事件<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><title>简易计算器</title><style>body {background-color: #eee;}#calculator {margin: 100px 0 0 150px;<!-- 简易计算器 --><div id="calculator"><p><input type="text" class="formerInput" value="1" /><span class="sign">+</span><input type="text" class="laterInput" value="1" /><span>=</span><span class="resultOutput">2</span></p><p><input type="button" value="+" onclick="addHandler();" /><input type="button" value="-" onclick="subtractHandler();" /><input type="button" value="×" onclick="multiplyHandler();" /><input type="button" value="÷" onclick="divideHandler();" /></p></div><script>// 获取元素var calculator = document.querySelector('#calculator');var formerInput = calculator.querySelector('.formerInput');var laterInput = calculator.querySelector('.laterInput');var sign = calculator.querySelector('.sign');var resultOutput = calculator.querySelector('.resultOutput');var btns = calculator.querySelectorAll('.btn');// 绑定事件for (var i = 0; i < btns.length; i++) {btns[i].onclick = function () {switch (this.title) {case 'add':addHandler();break;case 'subtract':subtractHandler();break;case 'multiply':multiplyHandler();break;case 'divide':divideHandler();break;}};}// 加function addHandler() {sign.innerHTML = '+';resultOutput.innerHTML = +formerInput.value + +laterInput.value; }// 减function subtractHandler() {sign.innerHTML = '-';resultOutput.innerHTML = formerInput.value - laterInput.value;}// 乘function multiplyHandler() {sign.innerHTML = '×';resultOutput.innerHTML = formerInput.value * laterInput.value;}// 除function divideHandler() {sign.innerHTML = '÷';resultOutput.innerHTML = formerInput.value / laterInput.value;}</script></body></html>⽅法四:提取函数<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><title>简易计算器</title><style>body {margin: 100px 0 0 150px;}</style></head><body><!-- 简易计算器 --><div id="calculator"><p><input type="text" class="formerInput" value="1" /><span class="sign">+</span><input type="text" class="laterInput" value="1" /><span>=</span><span class="resultOutput">2</span></p><p><input type="button" value="+" class="btn" title="add" /><input type="button" value="-" class="btn" title="subtract" /> <input type="button" value="×" class="btn" title="multiply" /> <input type="button" value="÷" class="btn" title="divide" /> </p></div><script>// 获取元素var calculator = document.querySelector('#calculator');var formerInput = calculator.querySelector('.formerInput');var laterInput = calculator.querySelector('.laterInput');var sign = calculator.querySelector('.sign');var resultOutput = calculator.querySelector('.resultOutput');var btns = calculator.querySelectorAll('.btn');// 绑定事件each(btns, function (index, elem ) {elem.onclick = function () {switch (this.title) {case 'add':addHandler();break;case 'subtract':subtractHandler();break;case 'multiply':multiplyHandler();break;case 'divide':divideHandler();break;}};});// 遍历function each(array, fn) {for (var i = 0; i < array.length; i++) {fn(i, array[i]);}}// 更新符号function updateSign(symbol) {sign.innerHTML = symbol;}// 加法function add(num1, num2) {return +num1 + +num2;}// 减法function subtract(num1, num2) {return num1 - num2;}// 乘法function multiply(num1, num2) {return num1 * num2;}// 除法function divide(num1, num2) {return num1 / num2;}// 输出结果}// 加function addHandler() {// sign.innerHTML = '+';updateSign('+');outputResult(add(formerInput.value, laterInput.value));}// 减function subtractHandler() {updateSign('-');outputResult(subtract(formerInput.value, laterInput.value)); }// 乘function multiplyHandler() {updateSign('×');outputResult(multiply(formerInput.value, laterInput.value)); }// 除function divideHandler() {updateSign('÷');outputResult(divide(formerInput.value, laterInput.value)); }</script></body></html>⽅法五:管理代码(找到组织)<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><title>简易计算器</title><style>body {background-color: #eee;}#calculator {margin: 100px 0 0 150px;}</style></head><body><!-- 简易计算器 --><div id="calculator"><p><input type="text" class="formerInput" value="1" /><span class="sign">+</span><input type="text" class="laterInput" value="1" /><span>=</span><span class="resultOutput">2</span></p><p><input type="button" value="+" class="btn" title="add" /><input type="button" value="-" class="btn" title="subtract" /> <input type="button" value="×" class="btn" title="multiply" /> <input type="button" value="÷" class="btn" title="divide" /> </p></div><script>// 获取元素var wrapElem = document.querySelector('#calculator');var calculatorElem = {formerInput: wrapElem.querySelector('.formerInput'),laterInput: wrapElem.querySelector('.laterInput'),sign: wrapElem.querySelector('.sign'),resultOutput: wrapElem.querySelector('.resultOutput'), btns: wrapElem.querySelectorAll('.btn')};// 绑定事件each(calculatorElem.btns, function (index, elem ) {elem.onclick = function () {switch (this.title) {case 'add':addHandler();break;case 'subtract':multiplyHandler();break;case 'divide':divideHandler();break;}};});// 遍历function each(array, fn) {for (var i = 0; i < array.length; i++) {fn(i, array[i]);}}// 更新符号function updateSign(symbol) {calculatorElem.sign.innerHTML = symbol;}var operation = {add: function(num1, num2) {return +num1 + +num2;},subtract: function(num1, num2) {return num1 - num2;},multiply: function(num1, num2) {return num1 * num2;},divide: function(num1, num2) {return num1 / num2;}};// 输出结果function outputResult(result) {calculatorElem.resultOutput.innerHTML = result;}// 加function addHandler() {// sign.innerHTML = '+';updateSign('+');outputResult(operation.add(calculatorElem.formerInput.value, terInput.value));}// 减function subtractHandler() {updateSign('-');outputResult(operation.subtract(calculatorElem.formerInput.value, terInput.value)); }// 乘function multiplyHandler() {updateSign('×');outputResult(operation.multiply(calculatorElem.formerInput.value, terInput.value)); }// 除function divideHandler() {updateSign('÷');outputResult(operation.divide(calculatorElem.formerInput.value, terInput.value)); }</script></body></html>⽅法六:OCP开放--封闭原则<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><title>简易计算器</title><style>body {background-color: #eee;}#calculator {margin: 100px 0 0 150px;}</style></head><!-- 简易计算器 --><div id="calculator"><p><input type="text" class="formerInput" value="1" /><span class="sign">+</span><input type="text" class="laterInput" value="1" /><span>=</span><span class="resultOutput">2</span></p><p><input type="button" value="+" class="btn" title="add" /><input type="button" value="-" class="btn" title="subtract" /><input type="button" value="×" class="btn" title="multiply" /><input type="button" value="÷" class="btn" title="divide" /><input type="button" value="%" class="btn" title="mod" /><input type="button" value="^" class="btn" title="power" /><!-- <input type="button" value="1/x" class="btn" title="invert" /> --></p></div><script>// 获取元素var wrapElem = document.querySelector('#calculator');var calculatorElem = {formerInput: wrapElem.querySelector('.formerInput'),laterInput: wrapElem.querySelector('.laterInput'),sign: wrapElem.querySelector('.sign'),resultOutput: wrapElem.querySelector('.resultOutput'),btns: wrapElem.querySelectorAll('.btn')};// 绑定事件each(calculatorElem.btns, function (index, elem ) {elem.onclick = function () {updateSign(this.value);outputResult(operate(this.title, calculatorElem.formerInput.value, terInput.value)); };});// 遍历function each(array, fn) {for (var i = 0; i < array.length; i++) {fn(i, array[i]);}}// 更新符号function updateSign(symbol) {calculatorElem.sign.innerHTML = symbol;}// 运算function operate(name, num1, num2) {if (!operation[name]) throw new Error('不存在名为' + name + '的运算⽅法!');return operation[name](num1, num2);}var operation = {add: function(num1, num2) {return +num1 + +num2;},subtract: function(num1, num2) {return num1 - num2;},multiply: function(num1, num2) {return num1 * num2;},divide: function(num1, num2) {return num1 / num2;},addOperation: function (name, fn) {if (!this[name]) {this[name] = fn;}return this;}};operation.addOperation('mod', function (num1, num2) {return num1 % num2;}).addOperation('power', function (base, power) {return Math.pow(base, power);function outputResult(result) {calculatorElem.resultOutput.innerHTML = result;}</script></body></html>⽅法七:模块化<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><title>简易计算器</title><style>body {background-color: #eee;}#calculator {margin: 100px 0 0 150px;}</style></head><body><!-- 简易计算器 --><div id="calculator"><p><input type="text" class="formerInput" value="1" /><span class="sign">+</span><input type="text" class="laterInput" value="1" /><span>=</span><span class="resultOutput">2</span></p><p><input type="button" value="+" class="btn" title="add" /><input type="button" value="-" class="btn" title="subtract" /><input type="button" value="×" class="btn" title="multiply" /><input type="button" value="÷" class="btn" title="divide" /><input type="button" value="%" class="btn" title="mod" /><input type="button" value="^" class="btn" title="power" /><input type="button" value="1/x" class="btn" title="invert" /></p></div><script>(function () {// 获取元素var wrapElem = document.querySelector('#calculator');var calculatorElem = {formerInput: wrapElem.querySelector('.formerInput'),laterInput: wrapElem.querySelector('.laterInput'),sign: wrapElem.querySelector('.sign'),resultOutput: wrapElem.querySelector('.resultOutput'),btns: wrapElem.querySelectorAll('.btn')};// 绑定事件each(calculatorElem.btns, function (index, elem ) {elem.onclick = function () {updateSign(this.value);outputResult(operate(this.title, calculatorElem.formerInput.value, terInput.value)); };});// 遍历function each(array, fn) {for (var i = 0; i < array.length; i++) {fn(i, array[i]);}}// 更新符号function updateSign(symbol) {calculatorElem.sign.innerHTML = symbol;}// 运算var operate = (function () {subtract: function(num1, num2) {return num1 - num2;},multiply: function(num1, num2) {return num1 * num2;},divide: function(num1, num2) {return num1 / num2;},addOperation: function (name, fn) {if (!operation[name]) {operation[name] = fn;}return operation;}};function operate(name) {if (!operation[name]) throw new Error('不存在名为' + name + '的运算⽅法!');return operation[name].apply(operation, [].slice.call(arguments, 1, arguments.length)); }operate.addOperation = operation.addOperation;return operate;})();operate.addOperation('mod', function (num1, num2) {return num1 % num2;}).addOperation('power', function (base, power) {return Math.pow(base, power);}).addOperation('invert', function (num) {return 1 / num;});// 输出结果function outputResult(result) {calculatorElem.resultOutput.innerHTML = result;}})();</script></body></html>。
javascript应用实例
javascript应用实例JavaScript应用实例:制作一个简单的计算器JavaScript是一种广泛应用于网页开发的脚本语言,它可以为网页添加动态效果和交互性。
在本文中,我们将介绍如何使用JavaScript 制作一个简单的计算器。
我们需要在HTML文件中创建一个表单,其中包含数字和运算符按钮以及一个显示结果的文本框。
代码如下:```<form><input type="text" id="result" readonly><br><input type="button" value="1" onclick="addNumber(1)"><input type="button" value="2" onclick="addNumber(2)"><input type="button" value="3" onclick="addNumber(3)"><input type="button" value="+" onclick="addOperator('+')"><br><input type="button" value="4" onclick="addNumber(4)"><input type="button" value="5" onclick="addNumber(5)"><input type="button" value="6" onclick="addNumber(6)"><input type="button" value="-" onclick="addOperator('-')"><br><input type="button" value="7" onclick="addNumber(7)"><input type="button" value="8" onclick="addNumber(8)"><input type="button" value="9" onclick="addNumber(9)"><input type="button" value="*" onclick="addOperator('*')"><br><input type="button" value="0" onclick="addNumber(0)"><input type="button" value="C" onclick="clearResult()"><input type="button" value="=" onclick="calculate()"><input type="button" value="/" onclick="addOperator('/')"></form>```在这个表单中,我们使用了四个数字按钮、四个运算符按钮和一个清除按钮。
Java实现简易计算器
Java实训作业题目:Java实现简易计算器学院:姓名:学号:班级:20 年月一、实验目的通过课程设计,主要要达到两个目的,一是检验和巩固专业知识、二是提高综合素质和能力。
此次课程设计实训主要是Java语言程序设计的实现。
通过该课程设计,可以将课堂上掌握的理论知识与处理数据的业务相结合,以检验自己掌握知识的宽度、深度及对知识的综合运用能力。
二、实验要求用Java编写一个简单的计算器,使其能够实现最基本的功能,如简单的加、减、乘、除;平方根,倒数,平方等功能。
三、详细内容1.界面设计界面设计使用GUI,其中有用到swing组件的TextField和Button,用到awt中的BorderLayout和GridLayout布局管理方式,其图形界面如图1-1所示:图1-1其中主要代码为:public mainWindow(){this.setTitle("计算器");//用户图形界面标题this.setVisible(true);//用户图形界面可缩小this.setResizable(false);//用户图形界面不可放大this.setSize(350,300);//设置用户图形界面的大小this.setLocation(400,150);//用户图形界面在屏幕中的显示位置JPanel panel1 = new JPanel();//新建一个画板JPanel panel2 = new JPanel();button1 = new JButton("1");...reset = new JButton("CE");Container container = this.getContentPane();container.add(panel2,BorderLayout.NORTH);container.add(panel1);panel1.setLayout(new GridLayout(5,4));//将画板1分为4行5列result.setEnabled(false);result.setFont(new Font("Dialog",Font.BOLD,25));//运算结果的字体大小result.setEditable(false);result.setHorizontalAlignment(SwingConstants.RIGHT);panel1.add(reciprocal);//分别将20个按钮依次添加到画板panel1中,并设置各自的大小reciprocal.setFont(new Font("Dialog",Font.PLAIN,20));...panel1.add(divide);divide.setFont(new Font("Dialog",Font.PLAIN,20));panel2.setLayout(new GridLayout());panel2.add(result);//画板panel2添加运算结果2.四则运算较为简单的实现了简单的加、减、乘、除运算,主要代码如下:ActionListener equal1 = new ActionListener(){ //实现四则运算public void actionPerformed(ActionEvent e){String str = result.getText();b = DatatypeConverter.parseDouble(str);{if(flag == "+")c = a + b;else if(flag == "-")c = a - b;else if(flag == "*")c = a * b;else if(flag == "/" || b != 0)c = a / b;}if(flag != "=")result.setText("" + c);elseresult.setText("零不能做除数!");a = 0;b = 0;c = 0;flag = "";}};3.其他功能另外添加了平方根,倒数,平方等功能,主要代码如下:平方根运算的实现:ActionListener sqrt1= new ActionListener(){public void actionPerformed(ActionEvent e){String str = result.getText();double i = DatatypeConverter.parseDouble(str);i = Math.sqrt(i);result.setText("" + i);}};倒数运算的实现:ActionListener reciprocal1 = new ActionListener(){ public void actionPerformed(ActionEvent e){String str = result.getText();double i = DatatypeConverter.parseDouble(str);i = 1/i;result.setText("" + i);}};平方运算的实现:ActionListener square1 = new ActionListener(){public void actionPerformed(ActionEvent e){String str = result.getText();double i = DatatypeConverter.parseDouble(str);i = i*i;result.setText("" + i);}};4.程序测试经测试发现本计算器基本功能均能实现,可正常运行计算,针对功能实现的代码部分过于简单,可以对其进行改善提高,方便用户使用!5.实训小结通过对计算器窗体的编写,熟悉了java图形用户界面的设计原理和程序结构,熟悉了java中awt和swing的组合。
js的综合实验案例
js的综合实验案例下面是一个简单的JavaScript综合实验案例,该案例使用了数组、循环、函数和事件处理。
题目:创建一个简单的计算器,可以执行基本的四则运算(加、减、乘、除)。
```html<!DOCTYPE html><html><head><title>JavaScript 计算器</title></head><body><h1>简单计算器</h1><input type="text" id="input1" placeholder="输入第一个数字"> <select id="operator"><option value="add">+</option><option value="subtract">-</option><option value="multiply"></option><option value="divide">/</option></select><input type="text" id="input2" placeholder="输入第二个数字"> <button onclick="calculate()">计算</button><p id="result"></p><script>function calculate() {// 获取输入值和运算符var num1 = parseFloat(('input1').value);var num2 = parseFloat(('input2').value);var operator = ('operator').value;// 验证输入值是否为数字if (isNaN(num1) isNaN(num2)) {alert('请输入数字!');return;}// 执行计算并显示结果switch (operator) {case 'add':result = num1 + num2; break;case 'subtract':result = num1 - num2; break;case 'multiply':result = num1 num2; break;case 'divide':if (num2 != 0) {result = num1 / num2; } else {alert('除数不能为零!'); return;}break;default:alert('无效的运算符!');}('result').innerText = '结果是:' + result; }</script></body></html>```。
js中简单计算器的代码
js中简单计算器的代码JS中实现一个简单的计算器并不困难,我们只需利用基本的数学运算符和JavaScript的语法即可。
下面是一个实现加、减、乘、除四则运算的计算器的JavaScript代码示例:```javascript// 获取计算器的元素var calculator = document.getElementById('calculator'); // 获取数字、运算符和结果显示区域的元素var num1 = document.getElementById('num1');var num2 = document.getElementById('num2');var operator = document.getElementById('operator');var result = document.getElementById('result');// 给运算符按钮添加事件处理函数var addButton = document.getElementById('add');addButton.addEventListener('click', function() {var n1 = parseFloat(num1.value);var n2 = parseFloat(num2.value);result.innerHTML = n1 + n2;});var subtractButton =document.getElementById('subtract');subtractButton.addEventListener('click', function() {var n1 = parseFloat(num1.value);var n2 = parseFloat(num2.value);result.innerHTML = n1 - n2;});var multiplyButton =document.getElementById('multiply');multiplyButton.addEventListener('click', function() { var n1 = parseFloat(num1.value);var n2 = parseFloat(num2.value);result.innerHTML = n1 * n2;});var divideButton = document.getElementById('divide'); divideButton.addEventListener('click', function() {var n1 = parseFloat(num1.value);var n2 = parseFloat(num2.value);result.innerHTML = n1 / n2;});```在以上代码中,我们定义了四个函数来处理加、减、乘、除四则运算。
java实验报告——简单计算器的编写五篇范文
java实验报告——简单计算器的编写五篇范文第一篇:java实验报告——简单计算器的编写JAVA实验报告——简单计算器的编写班级:学号:姓名:一、实验目的1.掌握java图形用户界面(GUI)的设计原理和程序结构2.能设计复核问题要求的图形用户界面程序3.掌握常用组件的事件接口4.应用awt和swing组件进行应用程序设计二、实验条件1.计算机一台2.java软件开发环境三、实验步骤1、编写代码:mport java.awt.*;import java.awt.event.*;import javax.swing.*;public class JCalculator extends JFrame implements ActionListener {private static final long serialVersionUID =-***457Lprivate class WindowCloser extends WindowAdapter {public void windowClosing(WindowEvent we){System.exit(0);}}int i;private final String[] str = { “7”, “8”, “9”, “/”, “4”, “5”, “6”, “*”, “1”,“2”, “3”, “-”, “.”, “0”, “=”, “+” };JButton[] buttons = new JButton[str.length]; JButton reset = new JButton(“CE”); JTextField display = new JTextField(“0”);public JCalculator(){super(“Calculator”);JPanel panel1 = new JPanel(new GridLayout(4, 4)); for(i = 0;i < str.length;i++){buttons[i] = new JButton(str[i]);panel1.add(buttons[i]);}JPanel panel2 = new JPanel(new BorderLayout()); panel2.add(“Center”, display);panel2.add(“East”, reset);getContentPane().setLayout(new BorderLayout()); getContentPane().add(“North”, panel2); getContentPane().add(“Center”, panel1);for(i = 0;i < str.length;i++)buttons[i].addActionListener(this);reset.addActionListener(this);display.addActionListener(this); addWindowListener(new WindowCloser()); setSize(800, 800);setVisible(true);pack();}public void actionPerformed(ActionEvent e){ Object target = e.getSource();String label = e.getActionCommand();if(target == reset)handleReset();else if(“0123456789.”.indexOf(label)> 0)handleNumber(label);elsehandleOperator(label);}boolean isFirstDigit = true;public void handleNumber(String key){if(isFirstDigit)display.setText(key);else if((key.equals(“.”))&&(display.getText().indexOf(“.”)< 0))display.setText(display.getText()+ “.”);else if(!key.equals(“.”))display.setText(display.getText()+ key);isFirstDigit = false;}public void handleReset(){display.setText(“0”);isFirstDigit = true;operator = “=”;}double number = 0.0;String operator = “=”;public void handleOperator(String key){if(operator.equals(“+”))number += Double.valueOf(display.getText());else if(operator.equals(“-”))number-= Double.valueOf(display.getText());else if(operator.equals(“*”))number *= Double.valueOf(display.getText());else if(operator.equals(“/”))number /= Double.valueOf(display.getText());else if(operator.equals(“=”))number = Double.valueOf(display.getText());display.setText(String.valueOf(number));operator = key;isFirstDigit = true;}public static void main(String[] args){new JCalculator();} }2、运行结果,见截图计算测试:123+456=579结果正确,程序无误。
js中简单计算器的代码
js中简单计算器的代码在JavaScript中,我们可以使用简单的语法来编写一个基本的计算器。
计算器可以执行加法、减法、乘法和除法等数学运算操作。
为了编写这个计算器程序,我们需要创建三个主要的函数,分别是获取输入、执行计算和输出结果。
首先定义一个由用户输入的数字和运算符组成的表达式,然后解析表达式,并在最终屏幕上显示计算结果。
下面是一个简单的计算器程序示例,可以执行加法、减法、乘法和除法四种基本运算:```jsfunction getInputValue() {var x = parseFloat(document.getElementById("input1").value); var y = parseFloat(document.getElementById("input2").value); var op = document.getElementById("operator").value;return [x, y, op];}function calculate() {var result;var [x,y,op] = getInputValue();if (op === "+") {result = x + y;} else if (op === "-") {result = x - y;} else if (op === "*") {result = x * y;} else if (op === "/") {result = x / y;}return result;}function displayResult() {var result = calculate();document.getElementById("result").innerHTML = result;}```这个计算器程序中,`getInputValue()`函数获取用户输入的数值和运算符,`calculate()`函数执行数学运算并返回计算结果,`displayResult()`函数将结果输出到屏幕上。
简易计算器实验报告
简易计算器实验报告一、实验目的本次实验的目的是设计并实现一个简易计算器,能够进行基本的四则运算(加、减、乘、除),以及处理括号的优先级运算,提高对程序设计和逻辑思维的理解与应用能力。
二、实验原理1、四则运算的优先级规则在数学运算中,先计算括号内的表达式,然后按照先乘除后加减的顺序进行计算。
乘除法的优先级高于加减法,如果在同一级运算中,按照从左到右的顺序进行。
2、数据结构的选择使用栈(Stack)数据结构来存储操作数和运算符。
栈具有先进后出的特点,非常适合处理表达式中的括号和优先级。
3、算法思路首先,将输入的表达式进行解析,将数字和运算符分别存储到不同的栈中。
然后,根据运算符的优先级进行计算,将计算结果重新压入栈中,直到表达式计算完毕。
三、实验设备及环境1、编程工具:选择了 Python 语言作为主要的编程工具,使用PyCharm 集成开发环境进行代码编写和调试。
2、操作系统:Windows 10 操作系统。
四、实验步骤1、定义数据结构定义两个栈,一个用于存储操作数(operandStack),一个用于存储运算符(operatorStack)。
2、表达式解析遍历输入的表达式字符串,将数字转换为整数并压入操作数栈,将运算符压入运算符栈。
遇到左括号直接压入运算符栈,遇到右括号则进行括号内的运算。
3、运算处理当运算符栈不为空时,取出栈顶的运算符和两个操作数进行计算。
根据运算符的优先级进行相应的运算,将结果压入操作数栈。
4、最终结果当表达式解析完毕后,操作数栈中的唯一元素即为表达式的计算结果。
五、代码实现```pythonclass SimpleCalculator:def __init__(self):selfoperandStack =selfoperatorStack =def calculate(self, expression):for char in expression:if charisdigit():selfoperandStackappend(int(char))elif char in '+/()':if char =='(':selfoperatorStackappend(char)elif char ==')':while selfoperatorStack-1!='(':operator = selfoperatorStackpop()operand2 = selfoperandStackpop()operand1 = selfoperandStackpop()result = selfperformOperation(operand1, operand2, operator)selfoperandStackappend(result)selfoperatorStackpop()else:while selfoperatorStack and selfhasHigherPrecedence(selfoperatorStack-1, char):operator = selfoperatorStackpop()operand2 = selfoperandStackpop()operand1 = selfoperandStackpop()result = selfperformOperation(operand1, operand2, operator)selfoperandStackappend(result)selfoperatorStackappend(char)while selfoperatorStack:operator = selfoperatorStackpop()operand2 = selfoperandStackpop()operand1 = selfoperandStackpop()result = selfperformOperation(operand1, operand2, operator)selfoperandStackappend(result)return selfoperandStackpop()def hasHigherPrecedence(self, op1, op2):if op1 in '/' and op2 in '+':return Trueelif op1 in '+' and op2 in '+':return Falseelif op1 in '/' and op2 in '/':return Falsereturn Falsedef performOperation(self, operand1, operand2, operator):if operator =='+':return operand1 + operand2elif operator =='':return operand1 operand2elif operator =='':return operand1 operand2elif operator =='/':if operand2 == 0:raise ValueError("除数不能为 0")return operand1 / operand2if __name__ =="__main__":calculator = SimpleCalculator()expression ="2 + 3 (4 1) / 2"result = calculatorcalculate(expression)print("计算结果:", result)```六、实验结果与分析1、测试用例及结果输入表达式:"2 + 3 4",计算结果:14输入表达式:"(2 + 3) 4",计算结果:20输入表达式:"5 2 3",计算结果:-1输入表达式:"10 / 2 + 1",计算结果:62、结果分析对于简单的四则运算表达式,计算器能够正确计算出结果。
eclipse实现简单计算器代码.
eclipse实现简单计算器代码.package Computer;import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;import java.util.LinkedList;import java.text.NumberFormat;public class Cacultor extends Frame implements ActionListener{/*** @param args*/NumberButton numberButton[];OperationButton operationButton[];Button 小数点按钮,正负号按钮,退格按钮,求倒数按钮,等号按钮,清零按钮;Panel panel;JTextField resultShow;String 运算符号[]={"+","-","*","/"};LinkedList 链表;boolean 是否按下等号=false;public Cacultor(){super("计算器");链表=new LinkedList();numberButton=new NumberButton[10];for(int i=0;i<=9;i++){numberButton[i]=new NumberButton(i);numberButton[i].addActionListener(this);}operationButton=new OperationButton[4];for(int i=0;i<4;i++){operationButton[i]=new OperationButton(运算符号[i]);operationButton[i].addActionListener(this);}小数点按钮=new Button(".");正负号按钮=new Button("+/-");等号按钮=new Button("=");求倒数按钮=new Button("1/x");退格按钮=new Button("退格");清零按钮=new Button("c");清零按钮.setForeground(Color.red);退格按钮.setForeground(Color.red);等号按钮.setForeground(Color.red);求倒数按钮.setForeground(Color.blue);正负号按钮.setForeground(Color.blue);小数点按钮.setForeground(Color.blue);退格按钮.addActionListener(this);清零按钮.addActionListener(this);等号按钮.addActionListener(this);小数点按钮.addActionListener(this);正负号按钮.addActionListener(this);求倒数按钮.addActionListener(this);resultShow=new JTextField(10);resultShow.setHorizontalAlignment(JTextField.RIGHT); resultShow.setForeground(Color.blue);resultShow.setFont(new Font("TimesRoman",Font.PLAIN,14)); resultShow.setBorder(newSoftBevelBorder(BevelBorder.LOWERED));resultShow.setBackground(Color.white);resultShow.setEditable(false);panel=new Panel();panel.setLayout(new GridLayout(4,5));panel.add(numberButton[1]);panel.add(numberButton[2]);panel.add(numberButton[3]);panel.add(operationButton[0]);panel.add(清零按钮);panel.add(numberButton[4]);panel.add(numberButton[5]);panel.add(numberButton[6]);panel.add(operationButton[1]);panel.add(退格按钮);panel.add(numberButton[7]);panel.add(numberButton[8]);panel.add(numberButton[9]);panel.add(operationButton[2]);panel.add(求倒数按钮);panel.add(numberButton[0]);panel.add(正负号按钮);panel.add(小数点按钮);panel.add(operationButton[3]);panel.add(等号按钮);add(panel,BorderLayout.CENTER);add(resultShow,BorderLayout.NORTH);addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){ System.exit(0);}});setVisible(true);setBounds(100,50,240,180);setResizable(false);validate();}//按钮事件的处理public void actionPerformed(ActionEvent e){if(e.getSource() instanceof NumberButton){NumberButton b=(NumberButton)e.getSource();if(链表.size()==0){int number=b.getNumber();链表.add(""+number);resultShow.setText(""+number);是否按下等号=false;}else if(链表.size()==1&&是否按下等号==false){ int number=b.getNumber();String num=(String)链表.getFirst();String s=num.concat(""+number);链表.set(0, s);resultShow.setText(s);}else if(链表.size()==1&&是否按下等号==true){int number=b.getNumber();链表.removeFirst();链表.add(""+number);是否按下等号=false;resultShow.setText(""+number);}else if(链表.size()==2){int number=b.getNumber();链表.add(""+number);resultShow.setText(""+number);}else if(链表.size()==3){int number=b.getNumber();String num=(String)链表.getLast();String s=num.concat(""+number);链表.set(2, s);resultShow.setText(s);}}else if(e.getSource()instanceof OperationButton){ OperationButton b=(OperationButton)e.getSource();if(链表.size()==1){String fuhao=b.get运算符号();链表.add(fuhao);}else if(链表.size()==2){String fuhao=b.get运算符号();链表.set(1, fuhao);}else if(链表.size()==3){String fuhao=b.get运算符号();String number1=(String)链表.getFirst();String number2=(String)链表.getLast();String 运算符号=(String)链表.get(1);try{double n2=Double.parseDouble(number2); double n=0;if(运算符号.equals("+")){n=n1+n2;}else if(运算符号.equals("-")){n=n1-n2;}else if(运算符号.equals("*")){n=n1*n2;}else if(运算符号.equals("/")){n=n1/n2;}链表.clear();链表.add(""+n);链表.add(fuhao);resultShow.setText(""+n);}catch(Exception ee){}}}else if(e.getSource()==等号按钮){是否按下等号=true;if(链表.size()==1&&链表.size()==2){ String num=(String)链表.getFirst(); resultShow.setText(""+num);}else if(链表.size()==3){String number1=(String)链表.getFirst(); String number2=(String)链表.getLast(); String 运算符号=(String)链表.get(1);try{double n2=Double.parseDouble(number2); double n=0;if(运算符号.equals("+")){n=n1+n2;}else if(运算符号.equals("-")){n=n1-n2;}else if(运算符号.equals("*")){n=n1*n2;}else if(运算符号.equals("/")){n=n1/n2;}resultShow.setText(""+n);链表.set(0, ""+n);链表.removeLast();链表.removeLast();}catch(Exception ee){}}}else if(e.getSource()==小数点按钮){if(链表.size()==0){是否按下等号=false;}else if(链表.size()==1){String dot=小数点按钮.getLabel();String num=(String)链表.getFirst();String s=null;if(num.indexOf(dot)==-1){s=num.concat(dot);链表.set(0, s);}else{s=num;}链表.set(0, s);resultShow.setText(s);}else if(链表.size()==3){String dot=小数点按钮.getLabel(); String num=(String)链表.getLast(); String s=null;if(num.indexOf(dot)==-1){s=num.concat(dot);链表.set(2, s);}else{s=num;}resultShow.setText(s);}}else if(e.getSource()==退格按钮){if(链表.size()==1){String num=(String)链表.getFirst();if(num.length()>=1){num=num.substring(0,num.length()-1); 链表.set(0, num);resultShow.setText(num);}else{链表.removeLast();resultShow.setText("0");}}else if(链表.size()==3){String num=(String)链表.getLast();if(num.length()>=1){num=num.substring(0,num.length()-1); 链表.set(2, num);resultShow.setText(num);}else{链表.removeLast();resultShow.setText("0");}}}else if(e.getSource()==正负号按钮){if(链表.size()==1){String number1=(String)链表.getFirst(); try{double d=Double.parseDouble(number1); d=-1*d;String str=String.valueOf(d);链表.set(0, str);resultShow.setText(str);}catch(Exception ee){}}else if(链表.size()==3){String number2=(String)链表.getLast();try{double d=Double.parseDouble(number2); d=-1*d;String str=String.valueOf(d);链表.set(2, str);resultShow.setText(str);}catch(Exception ee){}}}else if(e.getSource()==求倒数按钮){if(链表.size()==1||链表.size()==2){String number1=(String)链表.getFirst(); try{double d=Double.parseDouble(number1); d=1.0/d;String str=String.valueOf(d);链表.set(0, str);resultShow.setText(str);}catch(Exception ee){}}else if(链表.size()==3){String number2=(String)链表.getLast();try{double d=Double.parseDouble(number2); d=1.0/d;String str=String.valueOf(d);链表.set(0, str);resultShow.setText(str);}catch(Exception ee){}}}else if(e.getSource()==清零按钮){是否按下等号=false;resultShow.setText("0");链表.clear();}}public static void main(String[] args) {// TODO Auto-generated method stub new Cacultor();}}。
java简易计算器完整代码
java简易计算器完整代码import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextField;public class Calculate extends JFrame implements ActionListener {/****/private static final long serialVersionUID = 1L;/*** @param args*/float userFloata=0f;float userFloatb=0f;double result;JLabel label1 ;JLabel label2;JLabel label3;JTextField textField1;JTextField textField2;JTextField textField3;JButton addButton;JButton subtractButton;JButton rideButton;JButton divideButton;public Calculate(){setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setTitle("简易计算器");JPanel viewJPanel_1=new JPanel();JPanel viewJPanel_2=new JPanel();addButton=new JButton("加");addButton.addActionListener(this);viewJPanel_1.add(addButton);subtractButton=new JButton("减");subtractButton.addActionListener(this);viewJPanel_1.add(subtractButton);rideButton=new JButton("乘");rideButton.addActionListener(this);viewJPanel_1.add(rideButton);divideButton=new JButton("除");divideButton.addActionListener(this);viewJPanel_1.add(divideButton);label1=new JLabel("数据1:");viewJPanel_2.add(label1);textField1=new JTextField(5);textField1.addActionListener(this);viewJPanel_2.add(textField1);label2=new JLabel("数据2:");viewJPanel_2.add(label2);textField2=new JTextField(5);textField2.addActionListener(this);viewJPanel_2.add(textField2);label3=new JLabel("结果是:");viewJPanel_2.add(label3 );textField3=new JTextField(5);viewJPanel_2.add(textField3);setSize(420,120);setVisible(true);validate();getContentPane().add(viewJPanel_1,BorderLayout.NORTH);getContentPane().add(viewJPanel_2,BorderLayout.CENTER);}public void CalculateEventHandel(){try{userFloata= Float.parseFloat(textField1.getText().trim());userFloatb= Float.parseFloat(textField2.getText().trim());} catch (NumberFormatException e) {JOptionPane.showMessageDialog(this, "请输入数字型数据!");textField1.setText("");textField1.requestFocus();textField2.setText("");textField3.setText("");return;}}public static void main(String[] args) { // TODO Auto-generated method stubnew Calculate();//a.CalculateEventHandel();}public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stubif(e.getSource()==addButton){this.CalculateEventHandel();result=userFloata+userFloatb;// System.out.println(""+result);textField3.setText(""+result);}else if(e.getSource()==subtractButton){ this.CalculateEventHandel();result=userFloata-userFloatb;textField3.setText(""+result);}else if(e.getSource()==rideButton){this.CalculateEventHandel();result=userFloata*userFloatb;textField3.setText(""+result);}else if(e.getSource()==divideButton){this.CalculateEventHandel();result=userFloata/userFloatb;textField3.setText(""+result);}}}。
html+js实现简单的计算器代码(加减乘除)
html+js实现简单的计算器代码(加减乘除)html+js实现简单的计算器代码(加减乘除)<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title></title></head><body><table><tr><td><input type="button" value="add" onclick="setOp('+', 'add');"/></td><td><input type="button" value="miner" onclick="setOp('-', 'miner');"/></td><td><input type="button" value="times" onclick="setOp('*', 'times');"/></td><td><input type="button" value="divide" onclick="setOp('/', 'divide');"/></td></tr></table><table id="tb_calc" style="display:none;"><tr><td> <input id="x" type="text" style="width:100px" value="" name="x" /></td><td> <lable id="op" name="op"></lable> </td><td> <input id="y" type="text" style="width:100px" value="" name="y" /> </td><td> <input id="opTips" type="button" value="" onclick="calc();"/> </td><td> <lable id="z" name="z"></lable> </td></tr></table><script type="application/javascript">function setOp(op, opTips){var tb=document.getElementById("tb_calc");tb.style.display = "none";document.getElementById("x").value = "";document.getElementById("y").value = "";document.getElementById("z").innerText = "";document.getElementById("op").innerText = op;document.getElementById("opTips").value = opTips;tb.style.display = "block";}function calc(){var x = parseInt(document.getElementById("x").value);var y = parseInt(document.getElementById("y").value);var op = document.getElementById("op").innerText;var z = "";switch(op){case '+':z = x + y;break;case '-':z = x - y;break;case '*': ;z = x * y;break;case '/': ;z = x / y;break;default:z = '';}console.log(x, op, y, '=', z);document.getElementById("z").innerText = z;}</script></body></html>截图如下:以上这篇html+js实现简单的计算器代码(加减乘除)就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
JavaScript实现计算器的四则运算功能
JavaScript实现计算器的四则运算功能⽬录⼀、需求 + 最终实现1. 需求2. 说明:利⽤了字符串(split、replace)和数组(splice)的⽅法。
3. 代码实现⼆、实现步骤1. 版本⼀:实现基础加减乘除2. 版本⼆:实现⾼位数的运算3. ⽀持多次的运算三、思考后端思维前端思维结束⼀、需求 + 最终实现注:只是前端实现1. 需求需求来源是因为有⼀个做嵌⼊式 C/C++的基友做了⼀个远程计算器。
需求是要求⽀持输⼊⼀个四则混合运算公式的字符串,返回计算后的结果。
想看看⽤ C/C++封装过的 JavaScript 如果要实现这样⼀个功能最终效果(⽂章后我会讨论这两种实现思路,还望各位看官可以提出⼀些优化⽅案以及建议之类的~)。
2. 说明:利⽤了字符串(split、replace)和数组(splice)的⽅法。
主要是⽤到字符串切分为数组的⽅法 split、以及数组中插⼊删除的⽅法 splice。
字符串正则 replace ⽅法是考虑到⽤户的输⼊习惯可能有所不同,例如 1+2*3/4与 3 * 7 + 229。
⽀持:基础四则运算 3+6*5/6-3;⼩数四则运算 3.14 + 6 * 5 / 6 - 3.5;⾼位四则运算 99 * 94 - 6.35 + 100 / 1024;多次四则运算 3 * 3 + 3 * 16 - 7 - 5 + 4 / 2 + 22;以上综合不⽀持:带括号的运算 1 * (2 - 3);其他数学运算3. 代码实现/*** js四则混合运算计算器功能实现(约20⾏+ ⾯条代码)* @param {string} str 输⼊的四则运算字符串* @return {number} 输出结果*/const calculator = (str) => {// 定义添加字符函数const add = (arr, symbol) => {let length = arr.length;while (length > 1) {arr.splice(length - 1, 0, symbol); // 在每⼀项后⾯添加对应的运算符length--;}return arr; // ⽬的是得到⼀个改变长度的数组}const array = add(str.replace(/\s*/g,"").split('+'), '+').map(it => add(it.split('-'), '-').map(it => add(it.split('*'), '*').map(it => add(it.split('/'), '/')))).flat(3);;// 先运算乘除法['*', '/'].map(it => {while (array.includes(it)) {const index = array.findIndex(o => o === it);index > 0 && it === '*' ? array.splice(index - 1, 3, (Number(array[index - 1]) * Number(array[index + 1]))) : array.splice(index - 1, 3, (Number(array[index - 1]) / Number(array[index + 1])));}})// 再执⾏加减法,即从左⾄右的计算while (array.length > 1) {array[1] === '+' ? array.splice(0, 3, (Number(array[0]) + Number(array[2]))) : array.splice(0, 3, (Number(array[0]) - Number(array[2])));}return Number(array[0]).toFixed(2);}如果对 ES6 语法还算熟悉的话,应该可以轻松阅读代码的。
JS实现计算器带三角函数根号
JS实现计算器带三角函数根号以下是一个使用JavaScript实现的计算器代码,它包含了三角函数、开方等功能。
总字数超过1200字,但是实际代码量并不多,请自行补充。
```javascript//获取页面元素const display = document.getElementById("display");const buttons = document.getElementsByClassName("btn");//绑定按钮事件for (let i = 0; i < buttons.length; i++)buttons[i].addEventListener("click", buttonClick);//按钮点击事件处理函数function buttonClick(event)const buttonValue = event.target.innerHTML;if (buttonValue === "=")calculate(;} else if (buttonValue === "C")clear(;} else if (buttonValue === "√")squareRoot(;} else if (buttonValue === "sin")sine(;} else if (buttonValue === "cos")cosine(;} elseappendValue(buttonValue);}//向显示屏追加内容function appendValue(value)display.value += value;//清空显示屏function cleadisplay.value = "";//计算结果function calculattryconst result = eval(display.value); // 使用eval计算表达式display.value = result.toFixed(4); // 结果四舍五入保留4位小数} catch (error)display.value = "Error";}//计算平方根function squareRootryconst result = Math.sqrt(eval(display.value));display.value = result.toFixed(4);} catch (error)display.value = "Error";}//计算正弦值function sintryconst result = Math.sin(eval(display.value) * (Math.PI / 180)); // 将角度转换为弧度display.value = result.toFixed(4);} catch (error)display.value = "Error";}//计算余弦值function cosintryconst result = Math.cos(eval(display.value) * (Math.PI / 180)); // 将角度转换为弧度display.value = result.toFixed(4);} catch (error)display.value = "Error";}```HTML部分:```html<!DOCTYPE html><html><head><title>Calculator</title><link rel="stylesheet" type="text/css" href="style.css"> </head><body><div id="calculator"><input type="text" id="display" readonly> <div id="buttons"><div class="row"><button class="btn">7</button><button class="btn">8</button><button class="btn">9</button><button class="btn">/</button></div><div class="row"><button class="btn">4</button><button class="btn">5</button><button class="btn">6</button><button class="btn">*</button></div><div class="row"><button class="btn">1</button><button class="btn">2</button><button class="btn">3</button><button class="btn">-</button></div><div class="row"><button class="btn">0</button><button class="btn">.</button><button class="btn">+</button><button class="btn">=</button></div><div class="row"><button class="btn">C</button><button class="btn">√</button> <button class="btn">sin</button> <button class="btn">cos</button> </div></div></div><script src="script.js"></script> </body></html>```CSS部分:```css#calculatorwidth: 200px;margin: 0 auto;padding: 20px;#displaywidth: 100%;margin-bottom: 10px;padding: 5px;font-size: 20px;.rowdisplay: flex;.buttonflex: 1;margin-right: 5px;padding: 10px;font-size: 16px;```请注意,这只是一个简单的示例,实际的计算器功能可能更加复杂,需要根据具体需求进行适当的修改和扩展。
网页计算器--JS代码
网页计算器的界面:该计算其代码如下:<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head id="Head1" runat="server"><title>网页计算器</title></head><script type="text/javascript">var t;t = self.setInterval("ShowTime()", 10);var Exp = "";function ShowTime() {var Today = new Date(); //这条语句要放在该函数内,而不能作为全局变量hours = Today.getHours(); minutes = Today.getMinutes(); second = Today.getSeconds();if (hours < 10) hours = "0" + hoursif (minutes < 10) minutes = "0" + minutesif (second < 10) second = "0" + seconddocument.all.time.value = hours + ":" + minutes + ":" + second;}function MyFun() {alert(Exp);}//获取光标在ID为obj控件的位置,返回下标function getPos(obj) {obj.focus();var s = document.selection.createRange();s.setEndPoint("StartToStart", obj.createTextRange())return s.text.length;}//设置光标位置的函数function setCursor(ctrl, pos){if(ctrl.setSelectionRange){ctrl.focus();ctrl.setSelectionRange(pos,pos);}else if (ctrl.createTextRange){var range = ctrl.createTextRange();range.collapse(true);range.moveEnd('character', pos);range.moveStart('character', pos);range.select();}}//删除表达式中的元素function Delete() {var Len = document.all.In.value.length;Exp = document.all.In.value;var Arr = Exp.split("");var pos = getPos(In);Arr.splice(pos - 1, 1, "");var toStr = "";for(var j = 0; j < Arr.length; ++j)toStr += Arr[j];Exp = toStr;Arr = toStr.split("");document.all.In.value = toStr;setCursor(In,pos - 1);}//清除表达式function Clearn() {document.all.In.value = "";}function addParentheses(strObj) {var Temp = strObj;var Arr = Temp.split("");for (var i = 0; i < Arr.length; ++i) {if (Arr[i] == "s" || Arr[i] == "c" || Arr[i] == "t" || Arr[i] == "√"){if (Arr[i + 1] != "("){Arr.splice(i, 1, Arr[i] + "(");var toStr = "";for(var j = 0; j < Arr.length; ++j)toStr += Arr[j];Arr = toStr.split("");var Index = i + 2;if (Arr[Index] != "s" && Arr[Index] != "c" && Arr[Index] != "t" && Arr[Index] != "√"){var Bol = true;while (Bol) {if (Arr[Index + 1] == "+" || Arr[Index + 1] == "-" || Arr[Index + 1] == "*" || Arr[Index + 1] == "/" || Arr.length <= (Index + 1)){Arr.splice(Index, 1, Arr[Index] + ")");var toStr = "";for(var l = 0; l < Arr.length; ++l)toStr += Arr[l];Arr = toStr.split("");Bol = false;}++Index;}var S = "";for(var k = 0; k < Arr.length; ++k)S += Arr[k];S = Arr.toString();}//如果参数是函数else{var val = 0;var Bol = true;var hasPar = false;while (Bol){if (Arr[Index + 1] == "("){hasPar = true;val++;}if (Arr[Index + 1] == ")")--val;//没有括号的情况if (((Arr[Index + 1] == "+" || Arr[Index + 1] == "-" || Arr[Index + 1] == "*" || Arr[Index + 1] == "/") && !hasPar) || (Index + 1) >= Arr.length){Arr.splice(Index, 1, Arr[Index] + ")");var toStr = "";for(var j = 0; j < Arr.length; ++j)toStr += Arr[j];Arr = toStr.split("");Bol = false;}//有括号的情况if (val == 0 && hasPar){Arr.splice(Index + 1, 1,Arr[Index + 1] + ")");var toStr = "";for(var j = 0; j < Arr.length; ++j)toStr += Arr[j];Arr = toStr.split("");Bol = false;}++Index;}}}}var Str = "";for (var m = 0; m < Arr.length; ++m)Str += Arr[m];Exp = Str;}}//在表达式中添加表达式元素function addElement(Ele) {var Arr = new Array();Exp = document.all.In.value;var Index = getPos(In);if (Index >= Exp.length) {Exp += Ele;}else {Arr = Exp.split("");var Cha = Arr[Index];Arr.splice(Index, 1, Ele + Cha);var Str = "";for (var i = 0; i < Arr.length; ++i)Str += Arr[i];Exp = Str;}document.all.In.value = Exp;setCursor(In,Index + Ele.length);}function Input1() {addElement("1");}function Input2() {addElement("2");}function Input3() {addElement("3");}function Input4() {addElement("4");}function Input5() {addElement("5");}function Input6() {addElement("6");}function Input7() {addElement("7");}function Input8() {addElement("8");}function Input9() {addElement("9");}function Input0() {addElement("0");}function InputDot() {addElement(".");}function InputSin() {addElement("sin");}function InputCos() {addElement("cos");}function InputTan() {addElement("tan");}function InputSqtr() {addElement("√");}function InputAdd() {addElement("+");}function InputMin() {addElement("-");}function InputMult() {addElement("*");}function InputDiv() {addElement("/");}function InputPI() {addElement("3.141592"); }function InputLPar() {addElement("(");}function InputRPar() {addElement(")");}function InputLn() {addElement("ln");}function InputLog() {addElement("log");}function InputEql() {Exp = document.all.In.value;var Str = "";Str = Exp.replace(/sin/g, "s");Str = Str.replace(/cos/g, "c");Str = Str.replace(/tan/g, "t");addParentheses(Str);Exp = Exp.replace(/t/g, "Math.tan");Exp = Exp.replace(/s/g, "Math.sin");Exp = Exp.replace(/c/g, "Math.cos");Exp = Exp.replace(/√/g, "Math.sqrt");var result = eval(Exp);document.all.Restlt.value = result;}</script><body ><table border="8" bgcolor="rgb(50,200,100)" align= "center" cellspacing="0" cellpadding="0", width="250pt"><tr><td><label id = "Lab" ></label> 计算器</td></tr></table><table border="1" bgcolor="rgb(50,200,100)" align= "center" cellspacing="0" cellpadding="0", width="250pt"><tr><td><input id = "In" type = "text" style="width:160px" /></td><td><input id = "bs" type = "button" value = "Backspace" style="width:75px" onclick = "Delete();"/></td></tr></table><table border="1" bgcolor="rgb(50,200,100)" align= "center" cellspacing="0" cellpadding="0", width="250pt"><tr><td><input id = "Restlt" type = "text" style="width:110px" /></td><td><input id = "Clearn" type = "button" value = "Clearn" style="width:60px" onclick = "Clearn();" /></td><td><input id = "time" type = "text" style="width:60px" /></td></tr></table><table border="5" bgcolor="rgb(50,200,100)" align= "center" cellspacing="0" cellpadding="0", width="250pt"><tr><td><input type = "button" id = "N1" style="width:50px" value = "1" onclick = "Input1();"/></td><td><input type = "button" id = "N2" style="width:50px" value = "2" onclick = "Input2();" /></td><td><input type = "button" id = "N3" style="width:50px" value = "3" onclick = "Input3();" /></td><td><input type = "button" id = "Add" style="width:40px" value = "+" onclick ="InputAdd();" /></td><td><input type = "button" id = "Sub" style="width:40px" value = "-" onclick = "InputMin();"/></td></tr><tr><td><input type = "button" id = "N4" style="width:50px" value = "4" onclick = "Input4();"/></td><td><input type = "button" id = "N5" style="width:50px" value = "5" onclick = "Input5();" /></td><td><input type = "button" id = "N6" style="width:50px" value = "6" onclick = "Input6();" /></td><td><input type = "button" id = "Times" style="width:40px" value = "*" onclick = "InputMult();" /></td><td><input type = "button" id = "Divd" style="width:40px" value = "/" onclick = "InputDiv();" /></td></tr><tr><td><input type = "button" id = "N7" style="width:50px" value = "7" onclick = "Input7();"/></td><td><input type = "button" id = "N8" style="width:50px" value = "8" onclick = "Input8();" /></td><td><input type = "button" id = "N9" style="width:50px" value = "9" onclick = "Input9();" /></td><td><input type = "button" id = "Sqt" style="width:40px" value = "√" onclick = "InputSqtr();" /></td><td><input type = "button" id = "sin" style="width:40px" value = "sin" onclick = "InputSin();" /></td></tr><tr><td><input type = "button" id = "N0" style="width:50px" value = "0" onclick = "Input0();"/></td><td><input type = "button" id = "Dot" style="width:50px" value = "." onclick = "InputDot();" /></td><td><input type = "button" id = "Eql" style="width:50px" value = "=" onclick = "InputEql();" /></td><td><input type = "button" id = "cos" style="width:40px" value = "cos" onclick = "InputCos();" /></td><td><input type = "button" id = "tan" style="width:40px" value = "tan" onclick = "InputTan();" /></td></tr><tr><td><input type = "button" id = "PI" style="width:50px" value = "π" onclick = "InputPI();"/></td><td><input type = "button" id = "L_Par" style="width:50px" value = "(" onclick = "InputLPar();" /></td><td><input type = "button" id = "R_Par" style="width:50px" value = ")" onclick = "InputRPar();" /></td><td><input type = "button" id = "Ln" style="width:40px" value = "ln" onclick = "InputLn();" /></td><td><input type = "button" id = "Log" style="width:40px" value = "log" onclick = "InputLog();" /></td></tr></table><input id = "Input" type = "button" value = "click" onclick = "MyFun();" /> <form id="form1" runat="server"><div></div></form></body></html>。
用java编写一个简易的计算器代码
import java.awt.BorderLayout;import java.awt.Color;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JTextField;/使用java 语言开发一个简易计算器/public class TestJsq extends JFrame implements ActionListener, KeyListener {private JTextField jtf;private JButton jb_bk, jb_ce, jb_c;private String xs = "";private double sum = 0;private int fh;public static void main(String[] args) {new TestJsq().creatCUI();}public void creatCUI() {JFrame jf = new JFrame();jf.setTitle("计算器");jtf = new JTextField("0.");jtf.setHorizontalAlignment(JTextField.RIGHT);jf.add(jtf, BorderLayout.NORTH);JPanel jp_main = new JPanel(new BorderLayout());jf.add(jp_main);JPanel jp1 = new JPanel(new GridLayout(1, 3, 1, 1));jb_bk = new JButton("Backspace");jb_bk.setForeground(Color.RED);jb_bk.addActionListener(this);jb_ce = new JButton("CE");jb_ce.setForeground(Color.RED);jb_ce.addActionListener(this);jb_c = new JButton("C");jb_c.setForeground(Color.RED);jb_c.addActionListener(this);jp1.add(jb_bk);jp1.add(jb_ce);jp1.add(jb_c);jp_main.add(jp1, BorderLayout.NORTH);JPanel jp2 = new JPanel(new GridLayout(4, 5, 1, 1));String str[] = { "7", "8", "9", "/", "sqrt", "4", "5", "6", "", "%","1", "2", "3", "-", "1/x", "0", "+/-", ".", "+", "=" };for (int i = 0; i < 20; i++) {JButton jb = new JButton(str[i]);jb.addActionListener(this);jb.setForeground(Color.blue);if (i == 3 || i == 8 || i == 13 || i == 18 || i == 19) { jb.setForeground(Color.RED);}jp2.add(jb);}jp_main.add(jp2, BorderLayout.CENTER);jf.setResizable(false);jf.setBounds(50, 50, 350, 350);jf.setVisible(true);}Overridepublic void actionPerformed(ActionEvent e) {String s = e.getActionCommand();if (s.equals("CE") || s.equals("C")) {xs = "";jtf.setText("0.");} else if (s.equals("Backspace")) {String str = xs.substring(0, xs.length() - 1);xs = str;jtf.setText(xs);} else if (s.equals("7") || s.equals("8") || s.equals("9") || s.equals("4") || s.equals("5") || s.equals("6")|| s.equals("1") || s.equals("2") || s.equals("3")|| s.equals("0") || s.equals(".")) {xs = xs + s;jtf.setText(xs);} else if (s.equals("+/-")) {double x = Double.parseDouble(xs);xs="" + (-x);jtf.setText(xs);} else if (s.equals("/")) {fh = 4;int point = xs.indexOf(".");if (point = -1) {String strt = xs.substring(0, point);String z = xs.substring(point + 1, xs.length());int z_num = z.length();sum = Integer.decode(strt) + (double) (Integer.decode(z))/ (10 z_num);} else {sum = Integer.decode(xs);}xs = "";jtf.setText(null);} else if (s.equals("")) {fh = 3;int point = xs.indexOf(".");if (point = -1) {String strt = xs.substring(0, point);String z = xs.substring(point + 1, xs.length());int z_num = z.length();sum = Integer.decode(strt) + (double) (Integer.decode(z))/ (10 z_num);} else {sum = Integer.decode(xs);}xs = "";jtf.setText(null);} else if (s.equals("-")) {fh = 2;int point = xs.indexOf(".");if (point = -1) {String strt = xs.substring(0, point);String z = xs.substring(point + 1, xs.length());int z_num = z.length();sum = Integer.decode(strt) + (double) (Integer.decode(z))/ (10 z_num);} else {sum = Integer.decode(xs);}xs = "";jtf.setText(null);} else if (s.equals("+")) {fh = 1;int point = xs.indexOf(".");if (point = -1) {String strt = xs.substring(0, point);String z = xs.substring(point + 1, xs.length());int z_num = z.length();sum = Integer.decode(strt) + (double) (Integer.decode(z))/ (10 z_num);} else {sum = Integer.decode(xs);}xs = "";jtf.setText(null);} else if (s.equals("sqrt")) {double x = Double.parseDouble(xs);double x1 = Math.sqrt(x);xs = x1 + "";jtf.setText(xs);} else if (s.equals("%")) {double x = Double.parseDouble(xs);x=0.01 xx;xs=x+"";jtf.setText(xs);} else if (s.equals("1/x")) {if (xs == "0") {jtf.setText("除数不能为0");} else {double x = Double.parseDouble(xs);double x1 = 1 / x;xs = x1 + "";jtf.setText(String.valueOf(xs));}} else if (s.equals("=")) {if (fh = 0) {switch (fh) {case 1:int point1 = xs.indexOf(".");if (point1 = -1) {String s1 = xs.substring(0, point1);String z1 = xs.substring(point1 + 1, xs.length());int z1_num = z1.length();xs = "";double ss1 = Integer.decode(s1)+ (double) Integer.decode(z1) / (10 z1_num);sum = sum + ss1;} else {sum = sum + Integer.decode(xs);xs = "";}fh = 0;break;case 2:int point2 = xs.indexOf(".");if (point2 = -1) {String s2 = xs.substring(0, point2);String z2 = xs.substring(point2 + 1, xs.length());int z2_num = z2.length();xs = "";double ss2 = Integer.decode(s2)+ (double) Integer.decode(z2) / (10 z2_num);sum = sum - ss2;} else {sum = sum - Integer.decode(xs);xs = "";}fh = 0;break;case 3:int point3 = xs.indexOf(".");if (point3 = -1) {String s3 = xs.substring(0, point3);String z3 = xs.substring(point3 + 1, xs.length());int z1_num = z3.length();xs = "";double s4 = Integer.decode(s3)+ (double) Integer.decode(z3) / (10 z1_num);sum = sum s4;} else {sum = sum Integer.decode(xs);xs = "";}fh = 0;break;case 4:int point4 = xs.indexOf(".");if (point4 = -1) {String s4 = xs.substring(0, point4);String z4 = xs.substring(point4 + 1, xs.length());int z4_num = z4.length();xs = "";double s5 = Integer.decode(s4)+ (double) Integer.decode(z4) / (10 z4_num);sum = sum / s5;} else {sum = sum / Integer.decode(xs);xs = "";}fh = 0;break;default:break;}xs = String.valueOf(sum);jtf.setText(xs);fh = 0;} else {jtf.setText(null);}}}Overridepublic void keyPressed(KeyEvent e) {// TODO Auto-generated method stub}Overridepublic void keyReleased(KeyEvent e) { // TODO Auto-generated method stub }Overridepublic void keyTyped(KeyEvent e) { // TODO Auto-generated method stub }}。
简易计算器代码
<input type="button" value="-" name="b6" onClick="SetExp('-')">
</td>
<td>
<input type="button" value="*" name="b5" onClick="SetExp('*')">
</td>
</tr>
<tr align="center">
</td>
<td>
<input type="button" value="3" name="b3" onClick="SetExp('3')">
</td>
</tr>
<tr align="center">
<td>
<input type="button" value="4" onClick="SetExp('4')">
<td>
<input type="button" value="7" onClick="SetExp('7')">
</td>
<td>
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
用JSP编写的一个简易计算器实现代码如下:
<%@ page contentType="text/html;charset=gb2312"%>
<html>
<h1 align="center">简易计算器</h1>
<hr width="600">
<head>
<!--这是计算器的界面-->
<!--控制num1,num2不能为空,同时也不能是字符串-->
<script language="javascript">
//写一个函数验证用户是不是空提交
function checkNum()
{
//判断num1,num2是否为空
if(form1.numb1.value==""||form1.numb2.value=="")
{
window.alert("您输入的值为空!");
return false;
}
//判断num1,是不是一个数
if((Math.round(form1.numb1.value)!=form1.numb1.value)||(Math.round (form1.numb2.value)!=form1.numb2.value))
{
window.alert("您输入的值不合法!");
return false;
}
}
</script>
</head>
<center>
<body>
<%
//接收第一个数
String num1=request.getParameter("numb1");
//接收第二个数
String num2=request.getParameter("numb2");
//接收运算符号
String oper=request.getParameter("op");
Double dnum1=0.0;
Double dnum2=0.0;
Double result=0.0;
//java中String -> int
if(num1!=null&&num2!=null&&oper!=null)
{
dnum1=Double.parseDouble(num1);
dnum2=Double.parseDouble(num2);
//计算
if(oper.equals("+"))
{
//加
result=dnum1+dnum2;
}
else if(oper.equals("-"))
{
//减
result=dnum1-dnum2;
}
else if(oper.equals("×"))
{
//乘
result=dnum1*dnum2;
}
else
{
//除
result=dnum1/dnum2;
}
}
%>
<form name="form1" action="Calculator.jsp">
<p>请输入第一个数:<input type="text" name="numb1"></p>
<p>请输入第二个数:<input type="text" name="numb2"></p>
<p>请选择运算符:
<select name="op">
<option value=+>+</option>
<option value=->-</option>
<option value=×>×</option>
<option value=÷>÷</option>
</select></p>
<p><input type="submit" value="计算" onclick="return checkNum();"></p> </form>
<hr width="600">
<!--输出计算的结果-->
计算结果:<%=result%><!--表达式语法-->
</body>
</center>
</html>。