使用JSP制作一个超简单的网页计算器的实例分享
程序员文章站
2022-06-02 15:20:57
...
实现一个简单的计算器程序,要求:使用jsp+javabean模式实现。
项目源代码如下:
文件:calculator.jsp
项目源代码如下:
文件:calculator.jsp
<%@ page language="java" pageEncoding="UTF-8"%> <%@ page isErrorPage="true"%> <%@ page errorPage="calculator.jsp" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>简单的计算机</title> </head> <body> <%--创建Calculator对象--%> <jsp:useBean id="cal" class="cn.zq.domain.Calculator" /> <%--设置值 通配符*表示设置所有属性--%> <jsp:setProperty property="*" name="cal"/> <%-- 进行计算 --%> <c:if test="${empty pageContext.exception}"> <% cal.calculate(); %> </c:if> <hr/> <p>计算结果:${cal.firstNum } ${cal.operator } ${cal.secondNum } = ${cal.result }</p> <hr/> <%-- 构建url --%> <c:url var="formUrl" value="/calculator.jsp"/> <form action="${formUrl }" method="post"> <table border="1" cellpadding="2"> <tr> <td colspan="2" align="center">我的计算器</td> </tr> <tr> <td>第一个参数:</td> <td><input type="text" name="firstNum"/></td> </tr> <tr> <td>运算符:</td> <td> <select name="operator"> <option value="+">+</option> <option value="-">-</option> <option value="*">*</option> <option value="/">/</option> </select> </td> </tr> <tr> <td>第二个参数:</td> <td> <input type="text" name="secondNum"> </td> </tr> <tr> <td colspan="2"> <input type="submit" value="计算" /> </td> </tr> </table> </form> </body> </html>
本文使用的javabean代码如下:
package cn.zq.domain; public class Calculator { private String firstNum; private String operator; private String secondNum; private String result; public String getFirstNum() { return firstNum; } public void setFirstNum(String firstNum) { this.firstNum = firstNum; } public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator; } public String getSecondNum() { return secondNum; } public void setSecondNum(String secondNum) { this.secondNum = secondNum; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public Calculator() {} public Calculator(String firstNum, String operator, String secondNum, String result) { this.firstNum = firstNum; this.operator = operator; this.secondNum = secondNum; this.result = result; } public void calculate(){ if(operator != null && !operator.equals("")){ double first = new Double(firstNum); double second = new Double(secondNum); char oper = operator.charAt(0); switch (oper) { case '+': result = first + second + ""; break; case '-': result = first - second + ""; break; case '*': result = first * second + ""; break; case '/': result = first / second + ""; break; default: throw new RuntimeException("未知运算符!"); } } } }
最终完成的效果图如下:
更多使用JSP制作一个超简单的网页计算器的实例分享相关文章请关注PHP中文网!