1,CalculatorBean.java的实现封装数据和操作符.
import java.math.BigDecimal; public class CalculatorBean { private double firstNum; private double secondNum; private char operator = '+'; // int char byte short private double result; public double getFirstNum() { return firstNum; } public void setFirstNum(double firstNum) { this.firstNum = firstNum; } public double getSecondNum() { return secondNum; } public void setSecondNum(double secondNum) { this.secondNum = secondNum; } public char getOperator() { return operator; } public void setOperator(char operator) { this.operator = operator; } public double getResult() { return result; } public void setResult(double result) { this.result = result; } public void calculate() { switch (this.operator) { case '+': { this.result = this.firstNum + this.secondNum; break; } case '-': { this.result = this.firstNum - this.secondNum; break; } case '*': { this.result = this.firstNum * this.secondNum; break; } case '/': { if (this.secondNum == 0) { throw new RuntimeException("被除数不能为0!!!"); } this.result = this.firstNum / this.secondNum; // 四舍五入 this.result = new BigDecimal(this.result).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); break; } default: throw new RuntimeException("对不起,传入的运算符非法!!"); } } }
2,JSP显示层
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>计算器</title> </head> <body style="text-align: center;"> <jsp:useBean id="CalculatorBean" class="cn.itcast.CalculatorBean"></jsp:useBean> <jsp:setProperty name="CalculatorBean" property="*" /> <% CalculatorBean.calculate(); %> <br /> <hr> <br /> 计算结果是: <jsp:getProperty name="CalculatorBean" property="firstNum" /> <jsp:getProperty name="CalculatorBean" property="operator" /> <jsp:getProperty name="CalculatorBean" property="secondNum" /> = <jsp:getProperty name="CalculatorBean" property="result" /> <br /> <hr> <br /> <form action="/day09/calculator.jsp" method="post"> <table border="1" width="50%"> <tr> <td colspan="2"> 简单的计算器 </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>
效果图