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 = Parameter("first");//第⼀个数
String second = Parameter("second");//第⼆个数
String operator= Parameter("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);网页计算器html代码
if(!Result().equals("")&& Result()!= null){
out.print("<h2 style= 'color: blue'>");
out.print("计算结果:"+first+operator+second+" = "+Result());
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){ sult = result;
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。