JSP实现简单网页计算器
本文实例为大家分享了JSP实现简单网页计算器的具体代码,供大家参考,具体内容如下
一、构造一个简单的计算器,能够进行“+、—、*、/”运算
(1)编写jsp页面,用户通过表单输入两个操作数和运算符,调用该页面自身处理该表单,通过调用SimpleCalculator类的实例实现运算逻辑,并显示运算结果。
(2)实现下边的jsp网页计算器:
二、代码实现
(1)jsp页面
<%@page import="com.beans.SimpleCalculator"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>计算器</title>
</head>
<body>
<form action="" method="post">
第一个数:<input type="text" value="" name="first" size="25px"/>
<br /><br />
第二个数:<input type="text" value="" name="second" size="25px"/>
<br /><br />
<input type="submit" value="+" name="operator" size="3"/>
<input type="submit" value="-" name="operator" size="3"/>
<input type="submit" value="*" name="operator" size="3"/>
<input type="submit" value="/" name="operator" size="3"/>
<input type="reset" value="清除"/>
</form>
<br /><br />
<%
//获取表单中的数据进行运算
String first = request.getParameter("first");//第一个数
String second = request.getParameter("second");//第二个数
String operator = request.getParameter("operator");//运算符
String result = "" ;//运算结果
//判断运算符
if(operator.equals("+")) {
result = String.valueOf((Integer.valueOf(first) + Integer.valueOf(second) ));
}
if(operator.equals("-")) {
result = String.valueOf((Integer.valueOf(first) - Integer.valueOf(second) ));
}
if(operator.equals("*")) {
result = String.valueOf((Integer.valueOf(first) * Integer.valueOf(second) ));
}
if(operator.equals("/")) {
if(second.equals("0")) {
result = "除数不能为0";
}else {
result = String.valueOf((double)(Integer.valueOf(first) / (double)Integer.valueOf(second) ));
}
}
//定义一个计算器类
SimpleCalculator simpleCalculator = new SimpleCalculator();
simpleCalculator.setResult(result);
if( !simpleCalculator.getResult().equals("") && simpleCalculator.getResult() != null){
out.print("<h2 style= 'color: blue'>");
out.print("计算结果:"+first+operator+second+" = "+simpleCalculator.getResult());
out.print("<h4>");
}else{
out.print("计算错误");
}
%>
<br /><br />
</body>
</html>
(2)SimpleCalculator类
public class SimpleCalculator {
//定义变量
private String first;//第一个数
private String second;//第二个数
private String operator;//运算符
private String result;//运算结果
//定义set和get方法
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getSecond() {
return second;
}
public void setSecond(String second) {
this.second = second;
}
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}