完成两个操作数的运算,实现简单计数器的功能:
Index.html
<html>
<head>
<title>计算器</title>
</head>
<body>
<form action="calculate.jsp" method="post">
<table width="60%" border="1" align="center">
<tr>
<td colspan="2"><div align="center">计算器</div></td>
</tr>
<tr>
<td width="40%">第一个参数</td>
<td width="60%"><input type="text" name="first" ></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="second" ></td>
</tr>
<tr>
<td colspan="2"><div align="center">
<input type="submit" name="Submit" value="提交">
</div></td>
</tr>
</table>
</form>
</body>
</html>
calculate.jsp
<%@ page language="java" import="java.util.*" contentType="text/html;charset=gb2312"%>
<!-- 这里是声明,声明一个方法,用于计算两个操作数 -->
<%!
double result=0.0;
double calculate(String first,String second,String oper){
double one=Double.parseDouble(first);
double two=Double.parseDouble(second);
try{
if(oper.equals("+")) result=one+two;
else if(oper.equals("-")) result=one-two;
else if(oper.equals("*")) result=one*two;
else if(oper.equals("/")) result=one/two;
}catch(Exception ex){
System.out.println(ex.getMessage());
}
return result;
}
%>
<html>
<head><title>计算器</title> </head>
<body>
<!--这里是使用JSP脚本代码段,把计算结果打印输出 -->
<%
String first=request.getParameter("first");
String second=request.getParameter("second");
String oper=request.getParameter("operator");
double res=calculate(first,second,oper);
%>
<H2> <p align="center">计算结果为:
<%=first%>
<%=oper%>
<%=second%>=<%=res%>
</p>
</H2>
</body>
</html>