javabean
import java.math.BigDecimal;
//封装计算器数据的bean
public class CalculatorBean {
private String firstNum = "0";
private char operator = '+'; //int char
private String secondNum = "0";
private String result;
public String getFirstNum() {
return firstNum;
}
public void setFirstNum(String firstNum) {
this.firstNum = firstNum;
}
public char getOperator() {
return operator;
}
public void setOperator(char 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 void calculate(){
BigDecimal first = new BigDecimal(this.firstNum);
BigDecimal second = new BigDecimal(this.secondNum);
switch (this.operator) {
case '+':{
this.result = first.add(second).toString();
break;
}
case '-':{
this.result = first.subtract(second).toString();
break;
}
case '*':{
this.result = first.multiply(second).toString();
break;
}
case '/':{
if(second.doubleValue()==0){
throw new RuntimeException("被除数不能为0");
}
this.result = first.divide(second,20,BigDecimal.ROUND_HALF_UP).toString();
break;
}
default:
throw new RuntimeException("运算符只能是:+-*/ ");
}
}
}
<%@ 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="zgq.domain.CalculatorBean"/>
<jsp:setProperty name="calculatorBean" property="*"/>
<%
try{
calculatorBean.calculate();
}catch(Exception e){
out.write(e.getMessage());
}
%>
<br/>------------------------------------------------------------------------------------------------------------------------<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/>------------------------------------------------------------------------------------------------------------------------<br/>
<br/>
<form action="/day09/calculator.jsp" method="post">
<table width="40%" border="1">
<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>