案例:JSP计算器

<%@ 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">
<jsp:useBean id="forResult"	class="test.MathBean" scope="request">
	<jsp:setProperty name="forResult" property="*" />
</jsp:useBean>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>一简单的计数器</title>
</head>
<body>
	<center>
		<form action="test.jsp" method="post">
			<table border="1" width="300" bgcolor="ffffc0">
				<tr>
					<td>result</td>
					<td><%=forResult.getA()+forResult.getOperator()+forResult.getB()%>=<%=forResult.forResult()%></td>
				</tr>
				<tr>
					<td>number1</td>
					<td><input type="text" name="a"></td>
				</tr>
				<tr>
					<td>operator</td>
					<td>
						<select name="operator">
							<option value="+">+</option>
							<option value="-">-</option>
							<option value="*">*</option>
							<option value="/">/</option>
						</select>
					</td>
				</tr>
				<tr>
					<td>number2</td>
					<td><input type="text" name="b"></td>
				</tr>
				<tr>
					<td><input type="submit" value="sure"></td>
					<td><input type="reset" value="reset"></td>
				</tr>
			</table>
		</form>
	</center>
</body>
</html>

package test;

public class MathBean 
{
	private String a = "0.0";
	private String b = "0.0";
	private String operator = "+";
	
	public String getA()
	{
		return a;
	}
	
	public void setA(String a)
	{
		this.a = a;
	}
	
	public String getB()
	{
		return b;
	}
	
	public void setB(String b)
	{
		this.b = b;
	}
	
	public String getOperator()
	{
		return operator;
	}
	
	public void setOperator(String operator)
	{
		this.operator = operator;
	}
	
	public String forResult()
	{
		String intPattern0 = "[0-9]+";
		String intPattern = "-?" + intPattern0;
		String doublePattern = intPattern + "//." + intPattern0;
		doublePattern += "([eE]" + intPattern+")?";
		String numPattern = "("+intPattern+")|("+ doublePattern +")";
		if (!a.matches(numPattern))
		{
			return "First Value Is NaN!";
		}
		if (!b.matches(numPattern))
		{
			return "Second Value Is NaN!";
		}
		double one = Double.parseDouble(a);
		double two = Double.parseDouble(b);
		String result = "0.0";
		if (operator.equals("+"))
		{
			result = (one + two) + "";
		}else if (operator.equals("-"))
		{
			result = (one - two) + "";
		}else if (operator.equals("*"))
		{
			result = (one * two) + "";
		}else if (operator.equals("/")) 
		{
			if (Math.abs(two) < 10E-20) 
			{
				return "NaN";
			}
			result = (one / two) + "";
		}
		return result;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值