日期:2014-05-16  浏览次数:20529 次

JSP+JavaBean简单计算器
package bean;

public class CalculatorBean {
	private double firstNum;
	private double secondNum;
	private char operator='+';
	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;
			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>

</head>
<body>

	<jsp:useBean id="CalculatorBean" class="bean.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="/calculator/index.jsp" method="post"
		style="text-align: center">
		<table border="1" width="50%">
			<tr style="text-align: center">
				<td colspan="2">简单计算器</td>
				<td></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>