JavaBean
package com.itheima.domain; import java.math.BigDecimal; public class BigDecimalDemo { private double firstNum; private char fuHao='+'; private double secondNum; public double getFirstNum() { return firstNum; } public void setFirstNum(double firstNum) { this.firstNum = firstNum; } public char getFuHao() { return fuHao; } public void setFuHao(char fuHao) { this.fuHao = fuHao; } public double getSecondNum() { return secondNum; } public void setSecondNum(double secondNum) { this.secondNum = secondNum; } public double toResult(){ double result = 0; switch (fuHao) { case '+': result=new BigDecimal(firstNum).add(new BigDecimal(secondNum)).doubleValue(); break; case '-': result=new BigDecimal(firstNum).subtract(new BigDecimal(secondNum)).doubleValue(); break; case '*': result=new BigDecimal(firstNum).multiply(new BigDecimal(secondNum)).doubleValue(); break; case '/': if(secondNum!=0){ result=new BigDecimal(firstNum).divide(new BigDecimal(secondNum)).doubleValue(); }else{ throw new RuntimeException(); } break; default: break; } return result; } }
jsp页面
<%@page import="javax.servlet.jsp.tagext.TryCatchFinally"%> <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> <jsp:useBean id="bd" class="com.itheima.domain.BigDecimalDemo"></jsp:useBean> <jsp:setProperty property="*" name="bd"/> <% double a; try{ a=bd.toResult(); }catch(Exception e){ out.println("除法第二个数不能为0"); a=0;//如果出现异常,则打印出0 } %> <hr/> 您的计算结果是:<jsp:getProperty property="firstNum" name="bd"/> <jsp:getProperty property="fuHao" name="bd"/> <jsp:getProperty property="secondNum" name="bd"/> =<%=a %> <hr/> <form action="" method="get"> <table border='1' width='50%'> <tr> <td>您输入的第一个数</td> <td><input type="text" name="firstNum"></td> </tr> <tr> <td>您选择的运算符</td> <td> <select name="fuHao"> <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>